HashSet in Action

Hi Friends,

In today’s discussion we will see hashset in action. This is again one of the types of C# collection and very efficient. HashSet is basically a set as it implements ISet. HashSet is implemented internally using Hash tables. However, there is one catch with HashSet, there are no keys involved in it. Hence, we can’t lookup elements using key in hashset. Here, instead of key, values determine the things. so, in order to get any element in the hashset, we need to enumerate through.Then,why we use hashset. We use hashset for one quality reason and that is uniqueness.

Let’s consider, you have few elements in the collection and then you again added few more, then in that case there is no guarantee that it will prevent duplicate items to get added in the collection. In order to prevent it, we use hashset. HashSet guarantees that it won’t add any duplicate value to the collection.

and it will produce me the below output.


However, you can restrict the same before adding by putting extra line of code as shown below.

But, this is quite inefficient way as it will downgrade the performance if the list is big; As contains method examine the entire list till it matches the requirement. One way to fix this problem is by using hashset as shown below in the example.


Now, let’s consider one scenario where in mismatch in case and then you are trying to add the same.

then, it will fail and add the same in collection like


we have seen this problem earlier while dealing with dictionary. Now, quick fix around the same is using custom comparer as shown below.

now, lets consider a scenario where in you have two collections and you need to find the common value. In case of set it is called intersection of sets. Below in the example I have two sets having some common values.

This will print the below result.


Now, let’s see an union operation on the same. Union means either in A or in B.

This will print the below result.


Let’s look another scenario where in you want those values which are unique in both the lists.

This will give me below result.


Another scenario is subtraction of sets. Means find value that are only in 1st collection.

It gives me below output.


HashSet out of the box also gives flexibility to compare two sets, means check whether they are equal are not. It literally means whether values in two sets are equal or not as shown below.


i hope you have liked this piece. Thanks for joining me.

Rahul Sahay
Happy Coding

1,828 total views, 4 views today

This entry was posted in C# and tagged . Bookmark the permalink.