SoFunction
Updated on 2025-03-01

Usage of sets of C# collections

A set containing non-repeating elements is called a "set". The .NET Framework contains two sets, HashSet<T> and SortedSet<T>, both of which implement the ISet<T> interface. The HashSet<T> set contains an unordered list of non-repeating elements, and the SortedSet<T> set contains an ordered list of non-repeating elements.
The ISet<T> interface provides methods that can create collections, intersections, or give information that one 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 (("Williams"))
("Williams added");
if (!("McLaren"))
("McLaren was already in this set");

IsSubsetOf Verify that each element in traditionalTeams is included in companyTeams

if ((companyTeams))
{
("traditionalTeams is subset of companyTeams");
}

IsSupersetOf Verify whether there are elements in traditionalTeams that are not in companyTeams

if ((traditionalTeams))
{
("companyTeams is a superset of traditionalTeams");
}

Overlaps Verify whether there is an intersection

("Williams");
if ((traditionalTeams))
{
("At least one team is the same with the traditional " +
"and private teams");
}

Call UnionWith method to fill the new SortedSet<string> variables as a collection of companyTeams, privateTeams, and traditionalTeams

var allTeams = new SortedSet<string>(companyTeams);
(privateTeams);
(traditionalTeams);

();
("all teams");
foreach (var team in allTeams)
{
(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 ExceptWith

(privateTeams);
();
("no private team left");
foreach (var team in allTeams)
{
(team);
}

This is all about this article about the set of C# collections. I hope it will be helpful to everyone's learning and I hope everyone will support me more.