A collection that contains non-repeating elements is called a set. The. NET framework contains two sets hashset<t> and sortedset<t> they all implement the Iset<t> interface. The hashset<t> set contains an unordered list of non-repeating elements,sortedset<t> The set contains an ordered list of non-repeating elements.
The Iset<t> interface provides a way to create a collection, intersection, or information that is a superset or subset of another set.
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 is already in this set");
IsSubsetOf verifies that each element in the traditionalteams is contained in Companyteams
if (Traditionalteams.issubsetof (companyteams))
{
Console.WriteLine ("Traditionalteams is subset of Companyteams");
}
Issupersetof Verifying if there are elements in the traditionalteams that are not in Companyteams
if (Companyteams.issupersetof (traditionalteams))
{
Console.WriteLine ("Companyteams is a superset of Traditionalteams");
}
overlaps verify if there is an intersection
Traditionalteams.add ("Williams");
if (Privateteams.overlaps (traditionalteams))
{
Console.WriteLine ("At least one team was the same with the traditional" +
"and private teams");
}
call the Unionwith method to populate the new sortedset<string> variable with the Companyteams,privateteams,traditionalteams collection
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);
}
output (ordered):
Ferrari
Force India
Lotus
McLaren
Mercedes
Red Bull
Sauber
Toro Rosso
Williams
Each element is listed only once because the set contains only unique values.
Exceptwith method removes all private elements from the Exceptwith
Allteams.exceptwith (privateteams);
Console.WriteLine ();
Console.WriteLine ("No private team left");
foreach (var team in Allteams)
{
Console.WriteLine (team);
}
Collection of C # collections (set)