C Sharp HashSet

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# HashSet<T>

C# HashSet class can be used to store, remove or view elements. It does not store duplicate elements. It is suggested to use HashSet class if you have to store only unique elements. It is found in System.Collections.Generic namespace.

C# HashSet<T> example

Let's see an example of generic HashSet class that stores elements using Add() method and iterates elements using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class HashSetExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a set of strings  
  9.         var names = new HashSet<string>();  
  10.         names.Add("Sonoo");  
  11.         names.Add("Ankit");  
  12.         names.Add("Peter");  
  13.         names.Add("Irfan");  
  14.         names.Add("Ankit");//will not be added  
  15.           
  16.         // Iterate HashSet elements using foreach loop  
  17.         foreach (var name in names)  
  18.         {  
  19.             Console.WriteLine(name);  
  20.         }  
  21.     }  
  22. }  

Output:

Sonoo
Ankit
Peter
Irfan

C# HashSet<T> example 2

Let's see another example of generic HashSet class that stores elements using Collection initializer.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class HashSetExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a set of strings  
  9.         var names = new HashSet<string>(){"Sonoo""Ankit""Peter""Irfan"};  
  10.           
  11.         // Iterate HashSet elements using foreach loop  
  12.         foreach (var name in names)  
  13.         {  
  14.             Console.WriteLine(name);  
  15.         }  
  16.     }  
  17. }  

Output:

Sonoo
Ankit
Peter
Irfan