C# Generic Set

Like a generic list, sets can contain multiple values of the same type and are also just as flexible, but have the added feature that they cannot hold duplicate values. In C# there are two types of set, ‘HashSet’ and ‘SortedSet’, both of which will be discussed here.

The difference between these two types of set is that a ‘HashSet’ doesn’t maintain an order of the items within it, whereas a ‘SortedSet’ does.

Below is an example of how both of these types of set are declared, where ‘peopleHashSet’ and ‘peopleSortedSet’ are the names for the respective sets, with each being able to hold string values.

HashSet<string> peopleHashSet = new HashSet<string>();
SortedSet<string> peopleSortedSet = new SortedSet<string>();

Below are examples of how items can be added to these sets and then subsequently displayed in the console using a ‘foreach’ loop.

peopleHashSet.Add("George");
peopleHashSet.Add("Fred");
peopleHashSet.Add("Bob");
peopleHashSet.Add("Andew");

peopleSortedSet.Add("George");
peopleSortedSet.Add("Fred");
peopleSortedSet.Add("Bob");
peopleSortedSet.Add("Andrew");

Console.WriteLine("HashSet:");

foreach (string person in peopleHashSet)
{
    Console.WriteLine(person);
}

Console.WriteLine();
Console.WriteLine("SortedSet");

foreach (string person in peopleSortedSet)
{
    Console.WriteLine(person);
}

The output from the above is where the difference between the two sets can be seen, where the names in the ‘HashSet’ are in no particular order, but in the ‘SortedSet’ they are displayed alphabetically.

HashSet:
George
Fred
Bob
Andew

SortedSet
Andrew
Bob
Fred
George

As previously mentioned, a set cannot contain duplicate items, however, if an attempt is made to add a duplicate, no error is produced and no new item gets added.

Removing an item from a set is done in a similar fashion to adding.

peopleHashSet.Remove("Bob");
peopleSortedSet.Remove("Bob");

If there is a need to check to see if an item exists within a set, then the ‘Contains’ method can be used with both a ‘HashSet’ and a ‘SortedSet’. The ‘Contains’ method is used in the examples below to check for the existence of the name ‘George’ in both the sets and display a message to the console if it is found.

if (peopleHashSet.Contains("George"))
{
    Console.WriteLine("George is in the HashSet");
}

if (peopleSortedSet.Contains("George"))
{
    Console.WriteLine("George is in the SortedSet");
}

Further Reading