It is a cool collection available from C# 3.5. Like any other collection it can be used for resenting a set of value. It is an optimized set collection. It helps eliminating duplicate string or elements in collection. Whenever an Item is added in collection it will check whether this items are already there in collection If not then only it will add items.
Let’s take an example for the same.
static void Main(string args)
"Jalpesh", "Vishal", "Tushar", "Jalpesh"
foreach (var item in nameHashSet)
Now if you see the code carefully I have created HashSet of name(string type) with duplicate name like “Jalpesh” and then enumerate that collection with for loop and print items of collection with Console.WriteLine.
Now let’s run this application to see output.
If you see the output you can see that it has removed “Jalpesh” name duplication. So it was expected because HashSet automatically avoid duplication.
Advantages of HashSet:
- It’s automatically elements duplicate without giving any error.
- Searching is super fast as there is no duplication and also it uses hash base searching algorithms to find elements.
- You can also find items via indexes of items just like any other standard collections.
How to Add/Remove Element in HashSet:
There are multiple ways of initializing HashSet one of ways I have shown in above examples. But you can also use Add and Remove method to remove element in HashSet Collection like below.
Now when you run example it will output as follows
You can also use any standard collection methods in HashSet like Clear, Contains etc. There is a complete list of methods available with HashSet collection is available at following MSDN link.
You can find complete code for this blog post a following link.
That’s it. Hope you like it. Stay tuned for more!!