Understanding Sets in C#

I'm delighted to welcome you to our C# Sets lesson! In C#, sets are represented by the HashSet<T> collection, which can only hold unique elements. They're particularly useful when you need to ensure that elements in a collection appear only once.

In this lesson, you'll consolidate your knowledge of creating and operating on sets using HashSet<T>. You will learn about the advantages of using sets and how they enhance performance. Let's get started!

Creating and Manipulating Sets

Let's begin by creating a set in C#. This can be done using the HashSet<T> class.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Creating a HashSet and printing it
        HashSet<int> mySet = new HashSet<int> { 1, 2, 3, 4, 5, 5, 5 }; // Duplicates will be omitted
        Console.WriteLine(string.Join(", ", mySet)); // Output: 1, 2, 3, 4, 5
    }
}

C# provides methods to manipulate sets, such as Add, Contains, Remove, and Clear.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        HashSet<int> mySet = new HashSet<int> { 1, 2, 3, 4, 5 };

        // Adding an element
        mySet.Add(6); // `mySet` is now { 1, 2, 3, 4, 5, 6 }
        Console.WriteLine(mySet.Contains(1)); // Output: True, as `mySet` includes element 1

        // Removing an element
        mySet.Remove(1); // `mySet` becomes { 2, 3, 4, 5, 6 }
        Console.WriteLine(mySet.Contains(1)); // Output: False, as `mySet` doesn't include 1 anymore

        // Clearing the set
        mySet.Clear(); // `mySet` becomes an empty set
        Console.WriteLine(mySet.Count); // Output: 0
    }
}
  • Add: Adds a specified element to the set.
  • Contains: Checks if the specified element exists in the set.
  • Remove: Removes a specified element from the set.
  • Clear: Removes all elements from the set.
Set Operations

C# provides built-in methods for operations such as union, intersection, and difference for sets through LINQ.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        HashSet<int> set1 = new HashSet<int> { 1, 2, 3, 4 }; // First set
        HashSet<int> set2 = new HashSet<int> { 3, 4, 5, 6 }; // Second set

        // Set union
        var union = set1.Union(set2);
        Console.WriteLine(string.Join(", ", union)); // Output: 1, 2, 3, 4, 5, 6

        // Set intersection
        var intersection = set1.Intersect(set2);
        Console.WriteLine(string.Join(", ", intersection)); // Output: 3, 4

        // Set difference
        var difference = set1.Except(set2);
        Console.WriteLine(string.Join(", ", difference)); // Output: 1, 2
    }
}
  • Union: Combines elements from both sets, excluding any duplicates. In this case, the result is a set containing {1, 2, 3, 4, 5, 6}.
  • Intersect: Returns a set with only the elements that are common to both sets. For these sets, the intersection is {3, 4}.
  • Except: Returns a set containing elements that are in the first set but not in the second set. Here, the result is {1, 2} for set1.
Performance Benefits of Sets

One of the key advantages of sets is their faster performance in membership tests, thanks to their use of hashing.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Random random = new Random();
        HashSet<int> mySet = new HashSet<int>(Enumerable.Range(0, 10000000)); // A set of 10^7 elements
        List<int> myList = Enumerable.Range(0, 10000000).ToList(); // A list with the same elements and order

        // Warm-up
        mySet.Contains(-1);
        myList.Contains(-1);

        // Measure HashSet performance
        Stopwatch stopwatch = Stopwatch.StartNew();
        for (int i = 0; i < 1000; i++)
        {
            bool result = mySet.Contains(random.Next(10000000));
        }
        stopwatch.Stop();
        Console.WriteLine("Set: " + stopwatch.ElapsedMilliseconds + "ms");

        // Measure List performance
        stopwatch.Restart();
        for (int i = 0; i < 1000; i++)
        {
            bool result = myList.Contains(random.Next(10000000));
        }
        stopwatch.Stop();
        Console.WriteLine("List: " + stopwatch.ElapsedMilliseconds + "ms");
    }
}
  • Membership Test with HashSet<T>: Thanks to hash tables, sets can check for membership in constant time, leading to quick lookup times. The time taken for checking membership in the set is remarkably low.
  • Membership Test with List: Lists require a linear search to check for membership, which results in longer lookup times as the list grows. The time taken for checking membership in the list is noticeably higher.
Lesson Summary

Congratulations! You've just explored creating and manipulating sets, performing set operations, and reaping the performance benefits of sets in C#.

Remember, practice is key to solidifying your understanding. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal