HashSet .NET C#: Usage, Methods, and Example

Introduction

A hash set is an unordered list of distinct elements in C#. In.NET 3.5, this collection is released. It utilizes a hash table for storing and facilitates the implementation of sets. This collection is defined under System.Collections and belongs to the generic type collection.universal namespace. When we wish to stop duplicate pieces from being added to the collection, we typically utilize it. When compared to a list, the HashSet performs substantially better.

Crucial Information about HashSet in C#

The ICollection, IEnumerable, IReadOnlyCollection, ISet, IEnumerable, IDeserializationCallback, and ISerializable interfaces are all implemented by the HashSet class.

The element's order is not specified in a hash set. The HashSet's elements cannot be sorted.

Each element in a hash set needs to be distinct.

Numerous mathematical set operations are available, including difference, union, and intersection.

A hash set's capacity is the maximum amount of elements it can contain.

Since a hash set is a dynamic collection, adding new elements causes it to grow in size automatically.

You can only store elements of the same type in a hash set.

How can a HashSet be made?

The HashSet class offers seven distinct constructor types that can be used to generate a hash set; in this case, we'll just be using the HashSet() constructor.

HashSet()

This function utilizes the set type's default equality comparer to construct an empty instance of the HashSet class.

Step 1. Include System.Collections.Generic namespace in your program or application.

using System.Collections.Generic;

Step 2. Create a HashSet object using the HashSet class as shown below:

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

Step 3. Use the Add() method to add components to your hash set if you would like to do so. Additionally, you can use a collection initializer to store pieces in your hash set.

Step 4. A foreach loop is used to access the elements of the hash set. as demonstrated in the case below.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

Console.WriteLine("Element of the hashSet");
foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

Console.WriteLine();

// using collection initializer
// to initialize HashSet
var hashSet1 = new HashSet<int>() { 10, 100, 1000, 10000, 100000 };

Console.WriteLine("Element of the hashSet1");
foreach (var item in hashSet1)
{
    Console.WriteLine(item);
}

Element of the hashSet

How many items be taken out of the HashSet?

You are able to remove elements from the HashSet in HashSet. The HashSet<T> class offers three distinct ways for removing elements, which are as follows:

  • Remove(T): To remove a given element from a HashSet object, use the Remove(T) function.
  • RemoveWhere(Predicate): This function is used to eliminate from a HashSet collection all elements that satisfy the conditions specified by the given predicate.
  • Clear: To remove every element from a HashSet object, use this method.
var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

Console.WriteLine("Total elements: {0}", hashSet.Count);

hashSet.Remove("Jaimin");
Console.WriteLine();
Console.WriteLine("Removed Jaimin from the hashSet.");

Console.WriteLine();
Console.WriteLine("Total elements: {0}", hashSet.Count);

hashSet.Clear();
Console.WriteLine("Removed all of the elements from the hashSet.");

Console.WriteLine();
Console.WriteLine("Total elements: {0}", hashSet.Count);

Removed from hashset

Set Operations

Additionally, the HashSet class offers the following methods that can be used to manipulate sets in various ways:

UnionWith(IEnumerable): With this method, you can change the current HashSet object to include every element that exists in the given collection, in the HashSet itself, or in both.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

var hashSet1 = new HashSet<string>();
hashSet1.Add("Ashvin");
hashSet1.Add("Urmila");

hashSet.UnionWith(hashSet1);

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

unionwith

IntersectWith(IEnumerable): Using the IntersectWith(IEnumerable) function, you can change the current HashSet object so that it only contains elements that are found in both the designated collection and the object itself.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

var hashSet1 = new HashSet<string>();
hashSet1.Add("Ashvin");
hashSet1.Add("Urmila");
hashSet1.Add("Jaimin");
hashSet1.Add("Roshni");

hashSet.IntersectWith(hashSet1);

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

IntersectWith(IEnumerable):

ExceptWith(IEnumerable): This function eliminates from the current HashSet object every element in the given collection.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

var hashSet1 = new HashSet<string>();
hashSet1.Add("Ashvin");
hashSet1.Add("Urmila");
hashSet1.Add("Jaimin");
hashSet1.Add("Roshni");

hashSet.ExceptWith(hashSet1);

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

ExceptWith(IEnumerable):

SymmetricExceptWith: Occasionally, we may need to alter a HashSet in order to store distinct elements that differ between two sets. In order to achieve our goal, we can utilize the SymmetricExceptWith() method, which is where it comes into play.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");

var hashSet1 = new HashSet<string>();
hashSet1.Add("Ashvin");
hashSet1.Add("Urmila");
hashSet1.Add("Jaimin");
hashSet1.Add("Roshni");

hashSet.SymmetricExceptWith(hashSet1);

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

SymmetricExceptWith:

Duplicate Elements in a HashSet

Duplicate elements are not allowed in hash sets. If we attempt to add a duplicate element, it won't have any effect on the set. To make sure that each element can only appear once in the set, it employs a hashing mechanism.

var hashSet = new HashSet<string>();
hashSet.Add("Jaimin");
hashSet.Add("Roshni");
hashSet.Add("Dwisha");
hashSet.Add("Dwiti");
hashSet.Add("Jaimin");

foreach (var item in hashSet)
{
    Console.WriteLine(item);
}

Duplicate Elements in a HashSet

Advantages of C# HashSets

First off, because HashSets have a constant O(1) access time, they make speedy insertion and retrieval operations possible because they employ hash tables.

Additionally, we can use HashSets to reduce data redundancy in applications that prohibit duplicate components.

Finally, without having to loop through each element, HashSets can be helpful for rapidly determining whether an element is present in the set.

Disadvantages of C# HashSets

The sequence in which we iterate over the components of a hash set can change, which is a disadvantage of utilizing one.

Furthermore, not all circumstances where we need to store duplicate elements will lend themselves to the use of hash sets.

Compared to other data structures like lists or dictionaries, the HashSet data structure has fewer methods accessible.

Summary

This article teaches us that in C#, a HashSet may be a helpful tool for quickly inserting and retrieving entries. HashSets are another useful tool for storing unique elements.

Before choosing a solution, it's crucial to take our unique needs into account because not every scenario would call for it. It's also important to remember that a hash set does not preserve element order and does not support index-based element access.

We learned the new technique and evolved together.

Happy coding! 😊


Recommended Free Ebook
Similar Articles