在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
原文地址:http://www.cnblogs.com/xiaopin/archive/2011/01/08/1930540.html 感谢博主分享! NET 3.5在System.Collections.Generic命名空间中包含一个新的集合类:HashSet<T>。这个集合类包含不重复项的无序列表。这种集合称为“集(set)”。集是一个保留字,所以该类有另一个名称HashSet<T>。这个名称很容易理解,因为这个集合基于散列值,插入元素的操作非常快,不需要像List<T>类那样重排集合。 HashSet<T>类提供的方法可以创建合集和交集。表1列出了改变集的值的方法。 表1
表2列出了仅返回集的信息、不修改元素的方法。
在示例代码中,创建了3个字符串类型的新集,并用一级方程式汽车填充。HashSet<T>类实现了ICollection<T>接口。但是在该类中,Add()方法是显式实现的。Add()方法的区别是返回类型,它返回一个布尔值,说明是否添加了元素。如果该元素已经在集中,就不添加它,并返回false。 HashSet < string > companyTeams =new HashSet < string > (){ "Ferrari", "McLaren", "Toyota", "BMW","Renault", "Honda" }; HashSet < string > traditionalTeams =new HashSet < string > (){ "Ferrari", "McLaren" }; HashSet < string > privateTeams =new HashSet < string > (){ "Red Bull", "Toro Rosso", "Spyker","Super Aguri" }; if (privateTeams.Add("Williams")) Console.WriteLine("Williams added"); if (!companyTeams.Add("McLaren")) Console.WriteLine("McLaren was already in this set"); 两个Add()方法的输出写到控制台上: Williams added McLaren was already in this set
方法IsSubsetOf()和IsSupersetOf()比较集和实现了IEnumerable<T>接口的集合,返回一个布尔结果。这里,IsSubsetOf()验证traditionalTeams中的每个元素是否都包含在companyTeams中,IsSupersetOf()验证companyTeams 是否是traditionalTeams的超集。 if (traditionalTeams.IsSubsetOf(companyTeams)) { Console.WriteLine("traditionalTeams is " +"subset of companyTeams"); } if (companyTeams.IsSupersetOf(traditionalTeams)) { Console.WriteLine("companyTeams is a superset of " +"traditionalTeams"); } 这个验证的结果如下: traditionalTeams is a subset of companyTeams companyTeams is a superset of traditionalTeams
Williams也是一个传统队,因此这个队添加到traditionalTeams集合中: traditionalTeams.Add("Williams");//前面代码中privateTeams已经加入该元素 if (privateTeams.Overlaps(traditionalTeams)) { Console.WriteLine("At least one team is " +"the same with the traditional " +"and privateteams"); } 这有一个重叠,所以结果如下: At least one team is the same with the traditional and private teams.
调用UnionWith()方法,给变量allTeams填充了companyTeams、PrivateTeams和traditionalTeams的合集: HashSet < string > allTeams =new HashSet < string > (companyTeams); allTeams.UnionWith(privateTeams); allTeams.UnionWith(traditionalTeams); Console.WriteLine(); Console.WriteLine("all teams"); foreach (var team in allTeams) { Console.WriteLine(team); } 这里返回所有的队,但每个队都只列出一次,因为集只包含唯一值: Ferrari McLaren Toyota BMW Renault Honda Red Bull Toro Rosso Spyker Super Aguri Williams
方法ExceptWith()从allTeams集中删除所有的私人队: allTeams.ExceptWith(privateTeams); Console.WriteLine(); Console.WriteLine("no private team left"); foreach (var team in allTeams) { Console.WriteLine(team); } 集合中的其他元素不包含私人队: Ferrari McLaren Toyota BMW Renault Honda
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论