Open In App

C# HashSet

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

HashSet in C# is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate elements from being placed in the collection. The performance of the HashSet is much better in comparison to the list. 

  • HashSet is used to store the unique elements and doesn’t allow duplicates
  • It is better in performance.
  • It provides many mathematical set operations, such as intersection, union, and difference.

Example: Creating a HashSet

C#
// C# program to demonstrate HashSet functionality
using System;
using System.Collections.Generic;

class Geeks
{
    public static void Main()
    {
        // Create a HashSet 
        HashSet<int> hs = new HashSet<int>();

        // Add elements to the HashSet
        hs.Add(10);
        hs.Add(20);
        hs.Add(30);
        hs.Add(10); 

        // Display elements in the HashSet
        Console.WriteLine("Elements in the HashSet: ");
        foreach (int number in hs)
            Console.WriteLine(number);
    }
}

Output
Elements in the HashSet: 
10
20
30

Steps to Create a HashSet

The HashSet class provides different ways to create a HashSet. Jere we use the HashSet() constructor to create an instance of the HashSet class that is empty and uses the default equality comparer for the set type.

Step 1: Include System.Collections.Generic namespace

using System.Collections.Generic;

Step 2: Create a HashSet using the HashSet class

HashSet<Type_of_hashset> Hashset_name = new HashSet<Type_of_hashset>();

Performing Different Operations on HashSet

1. Adding Elements

We can add an element HashSet, then use the Add() method to add or we can also store elements in your HashSet using a collection initializer.

// Using Add method
set.Add(1);
set.Add(2);

// Using Collection Initializer

HaseSet<T> s = new HasSet<T>{1,2,3};

2. Accessing Elements

We generally use a foreach loop to iterate through the elements of a HashSet.

Example:

C#
// C# program to demonstrate accessing elements of a HashSet
using System;
using System.Collections.Generic;

class Geeks {

    static public void Main()
    {

        // Creating HashSet
        // Using HashSet class
        HashSet<string> set1 = new HashSet<string>();

        // Add the elements in HashSet
        // Using Add method
        set1.Add("C");
        set1.Add("C++");
        set1.Add("C#");
        set1.Add("Java");
        set1.Add("Ruby");
        Console.WriteLine("Elements of set1:");

        // Accessing elements of HashSet
        // Using foreach loop
        foreach(var val in set1)
        {
            Console.WriteLine(val);
        }

        // Creating another HashSet
        // using collection initializer
        // to initialize HashSet
        HashSet<int> set2 = new HashSet<int>() {1, 2, 3};
        
        // Display elements of set2
        Console.WriteLine("Elements of set2:");
        foreach(var value in set2)
        {
            Console.WriteLine(value);
        }
    }
}

Output
Elements of set1:
C
C++
C#
Java
Ruby
Elements of set2:
1
2
3

3. Removing Elements

We can remove elements from a HashSet using three methods:

  • Remove(T)This method is used to remove the specified element from a HashSet object.
  • RemoveWhere(Predicate): This method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet collection.
  • Clear: This method is used to remove all elements from a HashSet object.

Example:

C#
// C# program to demonstrate removing elements from a HashSet
using System;
using System.Collections.Generic;

class Geeks
{
    static public void Main()
    {
        // Create a HashSet
        HashSet<string> set = new HashSet<string>();

        // Add elements to HashSet
        set.Add("C");
        set.Add("C++");
        set.Add("C#");
        set.Add("Java");
        set.Add("Ruby");

        // Before removing elements
        Console.WriteLine("Elements (Before Removal): " 
                          + set.Count);

        // Remove an element
        set.Remove("C++");

        // After removal
        Console.WriteLine("Elements (After Removal): " 
                          + set.Count);
    }
}

Output
Elements (Before Removal): 5
Elements (After Removal): 4

4. Set Operations

The HashSet class also provides some methods that are used to perform different operations on sets and the methods are:

  • UnionWith(IEnumerable): This method is used to modify the current HashSet object to contain all elements that are present in itself, the specified collection, or both.
  • IntersectWith(IEnumerable)This method is used to modify the current HashSet object to contain only elements that are present in that object and the specified collection.
  • ExceptWith(IEnumerable)This method is used to remove all elements in the specified collection from the current HashSet object.

Example:

C#
// C# program to demonstrate set operations on HashSet
using System;
using System.Collections.Generic;

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

        // Union of two sets
        set1.UnionWith(set2);
        Console.WriteLine("After Union: " 
                          + string.Join(", ", set1));

        // Intersection of two sets
        set1.IntersectWith(new HashSet<int> { 3, 5 });
        Console.WriteLine("After Intersection: " 
                          + string.Join(", ", set1));

        // Difference of sets
        set1.ExceptWith(new HashSet<int> { 5 });
        Console.WriteLine("After Difference: " 
                          + string.Join(", ", set1));
    }
}

Output
After Union: 1, 2, 3, 5, 4
After Intersection: 3, 5
After Difference: 3

Important Points

  • The HashSet class implements the:
    • ICollection, IEnumerable, IReadOnlyCollection, ISet, IEnumerable, ISerializable interfaces.
    • IDeserializationCallback Class.
  • In HashSet, the order of the elements is not defined.
  • The capacity of a HashSet is the number of elements it can hold.
  • A HashSet is a dynamic collection, the size of the HashSet is automatically increased when the new elements are added.
  • In HashSet, we can only store the same type of elements.


Next Article

Similar Reads