Thursday, July 24, 2014

HashSet in C#

In this blog post we are going to learn about HashSet collection in C#. It is a cool collection available from C# 3.5. Like any other collection it can be used for representing 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.
using System;
using System.Collections.Generic;

namespace CSharpHashSet
{
    class Program
    {
        static void Main(string[] args)
        { 
            HashSet<string> nameHashSet=
                new HashSet<string>
                {
                    "Jalpesh", "Vishal", "Tushar", "Jalpesh"
                };
            foreach (var item in nameHashSet)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}
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.

hashtag-in-csharp-remove-duplicate

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:

  1. It’s automatically elements duplicate without giving any error.
  2. Searching is super fast as there is no duplication and also it uses hash base searching algorithms to find elements.
  3. 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.
nameHashSet.Add("Chirag");
nameHashSet.Remove("Tushar");
Now when you run example it will output as follows

hashset-add-remove-method.

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.

http://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx

You can find complete code for this blog post a following link.

https://github.com/dotnetjalps/CSharpHashSet

That’s it. Hope you like it. Stay tuned for more!!
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews