Understanding HashSet in C#

What is HashSet?

A HashSet<T> is a collection that contains unique elements only. It provides fast lookups and does not allow duplicates.

Key Features

  • No Duplicates: Automatically removes duplicate values.
  • Fast Performance: Faster than List<T> for lookups.
  • Unordered Collection: Does not maintain insertion order.
  • Supports Set Operations: Union, Intersect, Except, etc.

Basic Usage

using System;
using System.Collections.Generic;

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

        // Add elements
        numbers.Add(6);  // ✅ Added
        numbers.Add(3);  // ❌ Ignored (Duplicate)

        // Remove element
        numbers.Remove(2);

        // Check existence
        bool exists = numbers.Contains(3); // true

        // Iterate
        foreach (var num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

Set Operations

Union (Combine Two Sets)

var setA = new HashSet<int> { 1, 2, 3 };
var setB = new HashSet<int> { 3, 4, 5 };

setA.UnionWith(setB);  // setA = {1, 2, 3, 4, 5}

Intersection (Common Elements)

setA.IntersectWith(setB); // setA = {3}

Difference (Elements in A but not in B)

setA.ExceptWith(setB); // Removes elements of setB from setA

Symmetric Difference (Elements in either set, but not both)

setA.SymmetricExceptWith(setB);  // setA = {1, 2, 4, 5}

Performance Comparison

  • Lookup (Contains): HashSet = O(1), List = O(n)
  • Insertion: HashSet = O(1), List = O(n) if resizing is needed
  • Iteration: List is faster because it maintains order

When to Use HashSet?

  • When you need unique elements.
  • When you need fast lookups.
  • When you need to set operations.

Up Next
    Ebook Download
    View all
    Learn
    View all