NET 4 新增的 SortedSet 类

📅 2026/7/5 23:09:58
NET 4 新增的 SortedSet 类
以下我们来看 .NET 里 HashSet 的一些示例示例一 - 测试查找的功能var set new HashSetchar(我爱编程);Response.Write(set.Contains(我)); //TrueResponse.Write(set.Contains(你)); //False上述示例中我们能够将字符串甚至中文字传入 HashSetchar 的构造函数是因为 string 实现了 IEnumerablechar 接口而 HastSet 类也实现了 IEnumerableT。示例二 - 测试 HashSet 内置的一些好用方法SymmetricExceptWith: 仅包含该对象或指定集合中存在的元素但不可同时包含两者中的元素。UnionWith: 包含该对象本身和指定集合中存在的所有元素。ExceptWith: 从当前 HashSetT 对象中移除指定集合中的所有元素。IntersectWith: 仅包含该对象和指定集合中存在的元素。using System;using System.Collections.Generic;class HashSetDemo{static void Main(){HashSetchar setA new HashSetchar();HashSetchar setB new HashSetchar();setA.Add(A);setA.Add(B);setA.Add(C);setB.Add(C);setB.Add(D);setB.Add(E);Show(Initial content of setA: , setA);Show(Initial content of setB: , setB);setA.SymmetricExceptWith(setB); //把 setA、setB 各自特有、对方没有的元素列出来Show(setA after Symmetric difference with SetB: , setA);setA.UnionWith(setB); //把 setA、setB 的全部元素列出来 (union 并集)Show(setA after union with setB: , setA);setA.ExceptWith(setB); //把 setA 中所拥有的 setB 元素移除Show(setA after subtracting setB: , setA);Console.WriteLine();Console.Read();}static void Show(string msg, HashSetchar set){Console.Write(msg);foreach (char ch in set)Console.Write(ch );Console.WriteLine();}}执行结果图 3 测试 SymmetricExceptWith、UnionWith、ExceptWith 方法setA.IntersectWith(setB); //把 setA 中所拥有的 setB 元素列出Show(setA after intersect with setB: , setA);执行结果图 4 测试 IntersectWith 方法由于 HastSetT 实现了 IEnumerableT 接口因此我们可把其他任何 set 当作参数传入其他 set 类的运算方法里。此外LINQ 也有类似上述示例的 Intersect、Except、Union、Distinct 的 set 运算功能有兴趣比较两者特性的网友可参考 msdn 或网络上的文章 [5]。主要的差别在于LINQ set 运算始终返回新的 IEnumerableT 集合而 HashSetT 是修改当前的集合且 HashSet 提供了比较多的 set 相关算符。------------------------------------------------------------------------到了 .NET 4 才新建的 SortedSet 类除了有前述 HashSet 类所拥有的 SymmetricExceptWith、UnionWith、ExceptWith、IntersectWith 等好用的方法外还有「GetViewBetween (制定范围)」、「Max (取最大值)」、「Min (取最小值)」等新增的好用方法。以下我们来看 SortedSet 这三个方法的示例示例三 - 测试 GetViewBetween、Max、Min 方法using System;using System.Collections.Generic;using System.Linq; //此为 Max()、Min() 方法的必要引用var set new SortedSetint() { 5, 9, 2, 1, 2, 2, 3, 7, 4, 9, 9 };foreach (int element in set)Response.Write(string.Format( {0}, element));Response.Write(p);Response.Write(Max: set.Max() br);Response.Write(Min: set.Min() br);Response.Write(br取 2 ~ 5 之间的值: br);//只取值为 2 ~ 5 之间的元素var subSet set.GetViewBetween(2, 5);foreach (int i in subSet){Response.Write(i ,);}执行结果图 5 测试 SortedSet 类专属的 GetViewBetween、Max、Min 方法