原文链接
.NET 3.5在System.Collections.Generic命名空间中包含一个新的集合类:HashSet
HashSet
表 10-12
HashSet
Add() 如果某元素不在集合中,Add()方法就把该元素添加到集合中。在其返回值Boolean中,返回元素是否添加的信息
Clear() 方法Clear()删除集合中的所有元素
Remove() Remove()方法删除指定的元素
RemoveWhere() RemoveWhere()方法需要一个Predicate
CopyTo() CopyTo()把集合中的元素复制到一个数组中
ExceptWith() ExceptWith()方法把一个集合作为参数,从集中删除该集合中的所有元素
IntersectWith() IntersectWith()修改了集,仅包含所传送的集合和集中都有的元素
UnionWith() UnionWith()方法把传送为参数的集合中的所有元素添加到集中
表10-13列出了仅返回集的信息、不修改元素的方法。
表 10-13
HashSet
Contains() 如果所传送的元素在集合中,方法Contains()就返回true
IsSubsetOf() 如果参数传送的集合是集的一个子集,方法IsSubsetOf()就返回true
IsSupersetOf() 如果参数传送的集合是集的一个超集,方法IsSupersetOf()就返回true
Overlaps() 如果参数传送的集合中至少有一个元素与集中的元素相同,Overlaps()就返回true
SetEquals() 如果参数传送的集合和集包含相同的元素,方法SetEquals()就返回true
在示例代码中,创建了3个字符串类型的新集,并用一级方程式汽车填充。HashSet
HashSet < string > traditionalTeams &#61;new HashSet < string > (){ "Ferrari", "McLaren" };
HashSet < string > privateTeams &#61;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()方法的输出写到控制台上&#xff1a;
Williams added
McLaren was already in this set
方法IsSubsetOf()和IsSupersetOf()比较集和实现了IEnumerable
{
Console.WriteLine("traditionalTeams is " &#43;"subset of companyTeams");
}
if (companyTeams.IsSupersetOf(traditionalTeams))
{
Console.WriteLine("companyTeams is a superset of " &#43;"traditionalTeams");
}
这个验证的结果如下&#xff1a;
traditionalTeams is a subset of companyTeams
companyTeams is a superset of traditionalTeams
Williams也是一个传统队&#xff0c;因此这个队添加到traditionalTeams集合中&#xff1a;
if (privateTeams.Overlaps(traditionalTeams))
{
Console.WriteLine("At least one team is " &#43;"the same with the traditional " &#43;"and privateteams");
}
这有一个重叠&#xff0c;所以结果如下&#xff1a;
At least one team is the same with the traditional and private teams.
调用UnionWith()方法&#xff0c;给变量allTeams填充了companyTeams、PrivateTeams和traditionalTeams的合集&#xff1a;
allTeams.UnionWith(privateTeams);
allTeams.UnionWith(traditionalTeams);
Console.WriteLine();
Console.WriteLine("all teams");
foreach (var team in allTeams)
{
Console.WriteLine(team);
}
这里返回所有的队&#xff0c;但每个队都只列出一次&#xff0c;因为集只包含唯一值&#xff1a;
Ferrari
McLaren
Toyota
BMW
Renault
Honda
Red Bull
Toro Rosso
Spyker
Super Aguri
Williams
方法ExceptWith()从allTeams集中删除所有的私人队&#xff1a;
Console.WriteLine();
Console.WriteLine("no private team left");
foreach (var team in allTeams)
{
Console.WriteLine(team);
}
集合中的其他元素不包含私人队&#xff1a;
Ferrari
McLaren
Toyota
BMW
Renault
Honda