C# Hashset

In C#, Hashset is an unordered set of values that is optimized for fast retrieval of data. It provides set-oriented methods for determining whether the items it holds are a subset of those in another HashSet<T> object as well as computing the intersection and union of HashSet<T> objects. 

Hashset provides high-performance set operations and the set will return only unique elements, even when there are duplicate items in Hashset and those elements will not be in particular order.

The HashSet<T> class is optimized for performing set operations, such as determining set membership and generating the union and intersection of sets.

Few points to remember about hashset:

  • HashSet is a set implemented by hashing.
  • The HashSet Collection provides operations with high performance.
  • There are no duplicate elements in the HashSet Collection.
  • The size of hashset object will vary dynamically so we can add or remove elements from the hashset based on our requirements.
  • You insert items into a HashSet<T> collection by using the Add method, and you delete items by using the Remove method.
  • However, the real power of the HashSet<T> class is provided by the IntersectWith, UnionWith, and ExceptWith methods.

C# Hashset Declaration

HashSet<T> hset = new HashSet<T>();

Above, We have declared hashset as shown above where "T" is type parameter (T) as placeholders with an angle (<>) brackets, which indicates hashset is generic type and type parameter T is to represent a type of values to be accepted by hashset.

T can be any datatype like int,string etc.

C# Hashset example

Consider the below hashset example, in which we will try to add duplicate item in hashset but it will not show it

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		
		    HashSet<int> EmployeeIds = new HashSet<int>();
 
            // Add numbers to HashSet object 'EmployeeIds'
            EmployeeIds.Add(11);
            EmployeeIds.Add(12);
            EmployeeIds.Add(13);
		
            // Add again 11 to EmployeeIds
            EmployeeIds.Add(11);
 
            Console.WriteLine("Total count of the EmployeeIds= " + EmployeeIds.Count);
            foreach (int i in EmployeeIds)
            {
                Console.WriteLine(i);
            }
           
		   Console.WriteLine();
 
            int[] myIntArray = new int[4] { 11, 12, 13, 11 };
            Console.WriteLine("Total length of the myIntArray= " + myIntArray.Length);
            foreach (int i in myIntArray)
            {
                Console.WriteLine(i);
            }
	}
}

Output:

Total count of the EmployeeIds= 3
11
12
13

Total length of the myIntArray= 4
11
12
13
11

C# Hashset Example with Union

using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		    HashSet<int> evenNumbers = new HashSet<int>();
			HashSet<int> oddNumbers = new HashSet<int>();

			for (int i = 0; i < 5; i++)
			{
				// Populate numbers with just even numbers.
				evenNumbers.Add(i * 2);

				// Populate oddNumbers with just odd numbers.
				oddNumbers.Add((i * 2) + 1);
			}

			Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
			DisplaySet(evenNumbers);

			Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
			DisplaySet(oddNumbers);

			// Create a new HashSet populated with even numbers.
			HashSet<int> numbers = new HashSet<int>(evenNumbers);
			Console.WriteLine("numbers UnionWith oddNumbers...");
			numbers.UnionWith(oddNumbers);

			Console.Write("numbers contains {0} elements: ", numbers.Count);
			DisplaySet(numbers);


	}
	//display hashset
	public static void DisplaySet(HashSet<int> collection)
	{
		Console.Write("{");
		foreach (int i in collection)
		{
			Console.Write(" {0}", i);
		}
		Console.WriteLine(" }");
	}
}

Output:

evenNumbers contains 5 elements: { 0 2 4 6 8 }
oddNumbers contains 5 elements: { 1 3 5 7 9 }
numbers UnionWith oddNumbers...
numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }

When to use Hashset in C#?

Sometimes, we don't understand when we should use Hashset, when we can do same things with List, here are some of the points which may help us to choose when to use hashset

  • When Ordering is not important.
  • When you need unique elements only.
  • You can easily remove duplicates from List using Hashset
    List<string> duplicatedEnumrableStrings = new List<string> {"abc", "ghjr", "abc", "abc", "yre", "obm", "ghir", "qwrt", "abc", "vyeu"};
    HashSet<string> uniqueStrings = new HashSet(duplicatedEnumrableStrings);
    
    //output
    //uniqueStrings ={"abc", "ghjr", "yre", "obm", "qwrt", "vyeu"}?
  • Sets are really limited and with unique members, but they're really fast.

Share Tweet