Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
HashSet
3.
Set operations on HashSet
4.
FAQs
4.1.
What is a HashSet?
4.2.
When should I use HashSet C#
4.3.
Which is better HashSet or ArrayList?
4.4.
What is the space complexity of HashSet?
4.5.
Is HashSet a dynamic array?
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

HashSet in C#

Introduction

HashSet is an unordered collection of elements and a generic collection type. The HashSet supports the implementation of sets and uses the hash table for storage. The HashSet is available in the System.Collections.Generic namespace. It doesn’t allow duplicate values and can accept only one null value in the collection. The HashSet class implements the ICollection, IReadOnlyCollection, ISet, IEnumerable, IEnumerable, ISerializable interfaces, and IDeserializationCallback. The elements in a HashSet cannot be sorted because it is an unordered collection, and the order of elements is not defined. The HashSet increases dynamically as we add elements because the memory is allocated dynamically and doesn’t have any fixed size. The HashSet also supports set operations like intersection, union, and difference, along with creating, inserting and removing the elements. Let’s learn more about HashSet through the following example.

Must Read IEnumerable vs IQueryable, singleton design pattern in c# 

You can also read about the - hash function in data structure

HashSet

using System;
using System.Collections.Generic;

class HashSetExample {
	public static void Main()
	{
		HashSet<string> hashset1 = new HashSet<string>();
		hashset1.Add("Banana");
		hashset1.Add("Mango");
		hashset1.Add("Apple");
		hashset1.Add("Kiwi");

		Console.WriteLine("Elements of HashSet:");
        foreach(var value in hashset1)
        {
        	Console.WriteLine(value);
		}

		hashset1.Remove("Mango");

		Console.WriteLine("Elements of HashSet after removing an element:”);
		foreach(var value in hashset1)
        {
        	Console.WriteLine(value);
		}
	}
}


Output

Elements of HashSet:

Banana

Mango

Apple

Kiwi

Elements of HashSet after removing and element:

Banana

Apple

Kiwi

We created a string HashSet using the HashSet in Generic collection in System in the above code. We can add elements to the HashSet using the add() method and remove any element using the Remove() method as shown in the code. The output after and before removing the element is as shown above.

Set operations on HashSet

HashSet supports performing set operations on the set. The methods supported by it are

  • UnionWith() - combines all the elements in two or more HashSets and stores them in a single HashSet.
  • IntersectWith() - identifies the same elements in different HashSets and stores them in a single HashSet.
  • ExceptWith() - compares the HashSets and stores the elements that are not present in both the HashSets. 


Let’s learn how to perform all these operations through the following code.

using System;
using System.Collections.Generic;

class HashSetExample {
	public static void Main()
	{
		HashSet<string> hashset1 = new HashSet<string>();
		hashset1.Add("Banana");
		hashset1.Add("Mango");
		hashset1.Add("Apple");
		hashset1.Add("Kiwi");

		HashSet<string> hashset2 = new HashSet<string>();
		hashset2.Add("Banana");
		hashset2.Add("Apricot");
		hashset2.Add("Apple");
		hashset2.Add("Lichi");

		// ExceptWith method
		hashset1.ExceptWith(hashset2);
       Console.WriteLine("ExceptWith method");
		foreach(var ele in hashset1)
		{
			Console.WriteLine(ele);
		}

		// UnionWith method
		hashset1.UnionWith(hashset2);
        Console.WriteLine("UnionWith method");
        foreach(var ele in hashset1)
        {
             Console.WriteLine(ele);
        }

		// IntersectWith method
		hashset1.IntersectWith(hashset2);
        Console.WriteLine("IntersectWith method");
        foreach(var ele in hashset1)
        {
        	Console.WriteLine(ele);
        }
	}
}


Output

ExceptWith method

Mango

Kiwi

UnionWith method

Apricot

Mango

Banana

Kiwi

Apple

Lichi

IntersectWith method

Apricot

Banana

Apple

Lichi

We created two HashSets, “hashset1”, and “hashset2” in the above code and inserted a few elements into them. After performing the operations ExceptWith(), UnionWith(), and IntersectWith() methods, the output will be as shown above.

Check out this problem - Duplicate Subtree In Binary Tree

FAQs

What is a HashSet?

HashSet is an unordered collection of elements and a generic collection type. The HashSet supports the implementation of sets and uses the hash table for storage. It doesn’t allow duplicate values and can accept only one null value in the collection.

When should I use HashSet C#

HashSet is generally used for unique data with high-performance operations. You can use a HashSet when you want your data to be unique without any duplicate values, which performs the searching operation for elements faster.

Which is better HashSet or ArrayList?

The HashSet doesn’t allow duplicate values, while the ArrayList allows them. So the HashSet can be faster for search operations. But the HashSet doesn’t support sorting, so that ArrayList can be better for the ordered collection.

What is the space complexity of HashSet?

The space complexity of a HashSet is O(1) because it uses a constant amount of space when it iterates over the HashSet.

Is HashSet a dynamic array?

The HashSet increases dynamically as we add elements because the memory is allocated dynamically and doesn’t have any fixed size. So the HashSet can be considered as a dynamic array.

Key Takeaways

We have discussed the concept of the HashSet in C# in this article with clear examples and a code. You can now use the HashSet in your code and execute different operations.

Hey Ninjas! We hope this blog helped you better understand the HashSet in C#. Please check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems. Please upvote our blog to help the other ninjas grow.

Happy Coding!

Live masterclass