C# Sets

Like lists and arrays, sets can contain multiple values of the same type. They share the flexibility of lists, 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. In order to utilise sets, there needs to be a ‘using’ directive for ‘System.Collections.Generic’.

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 ‘nameHashSet’ and ‘nameSortedSet’ are the names for the respective sets, with each being able to hold string values.

HashSet<string> nameHashSet = new HashSet<string>();
SortedSet<string> nameSortedSet = 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.

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

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

Console.WriteLine("HashSet:");

foreach (string name in nameHashSet)
{
    Console.WriteLine(name);
}

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

foreach (string name in nameSortedSet)
{
    Console.WriteLine(name);
}

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.

nameHashSet.Remove("Bob");
nameSortedSet.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 (nameHashSet.Contains("George"))
{
    Console.WriteLine("George is in the HashSet");
}

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

Further Reading

Navigation