C#集合之集(set)
包含不重復元素的集合稱為“集(set)”。.NET Framework包含兩個集HashSet<T>和SortedSet<T>,它們都實現ISet<T>接口。HashSet<T>集包含不重復元素的無序列表,SortedSet<T>集包含不重復元素的有序列表。
ISet<T>接口提供的方法可以創建合集,交集,或者給出一個是另一個集的超集或子集的信息。
var companyTeams = new HashSet<string>() { "Ferrari", "McLaren", "Mercedes" };
var traditionalTeams = new HashSet<string>() { "Ferrari", "McLaren" };
var privateTeams = new HashSet<string>() { "Red Bull", "Lotus", "Toro Rosso", "Force India", "Sauber" };
if (privateTeams.Add("Williams"))
Console.WriteLine("Williams added");
if (!companyTeams.Add("McLaren"))
Console.WriteLine("McLaren was already in this set");
IsSubsetOf驗證traditionalTeams中的每個元素是否都包含在companyTeams中
if (traditionalTeams.IsSubsetOf(companyTeams))
{
Console.WriteLine("traditionalTeams is subset of companyTeams");
}
IsSupersetOf驗證traditionalTeams中是否有companyTeams中沒有的元素
if (companyTeams.IsSupersetOf(traditionalTeams))
{
Console.WriteLine("companyTeams is a superset of traditionalTeams");
}
Overlaps驗證是否有交集
traditionalTeams.Add("Williams");
if (privateTeams.Overlaps(traditionalTeams))
{
Console.WriteLine("At least one team is the same with the traditional " +
"and private teams");
}
調用UnionWith方法把新的 SortedSet<string>變量填充為companyTeams,privateTeams,traditionalTeams的合集
var allTeams = new SortedSet<string>(companyTeams);
allTeams.UnionWith(privateTeams);
allTeams.UnionWith(traditionalTeams);
Console.WriteLine();
Console.WriteLine("all teams");
foreach (var team in allTeams)
{
Console.WriteLine(team);
}
輸出(有序的):
Ferrari
Force India
Lotus
McLaren
Mercedes
Red Bull
Sauber
Toro Rosso
Williams
每個元素只列出一次,因為集只包含唯一值。
ExceptWith方法從ExceptWith中刪除所有私有元素
allTeams.ExceptWith(privateTeams);
Console.WriteLine();
Console.WriteLine("no private team left");
foreach (var team in allTeams)
{
Console.WriteLine(team);
}
C#集合之集(set)