Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




C# - HASHSET


A HashSet is a Collection that can also hold multiple values. And a HashSet is unordered and doesn't allow duplicate values.


A HashSet is created in the same way a List is created.


var x = new HashSet<string>();

The above HashSet is used to hold values of string type.


Creating an empty HashSet


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new HashSet<string>(); 
        
        x.Add("Tom");
        x.Add("John");
        x.Add("C#");
        
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  Tom
  John
  C#

So, in the above code, we have declared an empty HashSet that is used to hold values of string data type.


var x = new HashSet<string>();

Then we have used the Add() method to add the values to the HashSet.


x.Add("Tom");
x.Add("John");
x.Add("C#");

And finally, used the foreach loop to print the contents of the HashSet.


foreach (var data in x)
{
	System.Console.WriteLine(data);
}

HashSet doesn't accept duplicates


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new HashSet<string>(); 
        
        x.Add("Tom");
        x.Add("John");
        x.Add("C#");
        x.Add("John");
        
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  Tom
  John
  C#

So, in the above code we have created a HashSet using the values, "Tom", "John", "C#" and "John".


var x = new HashSet<string>();

Now, if we see the output,

Output :



  Tom
  John
  C#

You can see only three values are printed.


This is because in the above HashSet, the name John is present twice.


And since a HashSet doesn't accept duplicates, the name John is not inserted to the HashSet twice.


And we see the above output with John present only once.