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




C# - REMOVE FROM HASHSET


How to remove an element from the HashSet by its name/value?


Let us say, we have a HashSet that contains three names, Mohan, Kriti and Salim. And we want to remove Kriti from the HashSet.


It can be done with the Remove() Method


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new HashSet<string>(); 
        
        x.Add("Mohan");
        x.Add("Kriti");
        x.Add("Salim");
        
        x.Remove("Kriti");
        
        foreach (var i in x)  
        {  
            System.Console.WriteLine(i);  
        }
    }    
}


Output :



  Mohan
  Salim

So, in the above code we have created a HashSet and initialised to the variable x.


var x = new HashSet<string>();

x.Add("Mohan");
x.Add("Kriti");
x.Add("Salim");

Below is how the values are positioned in the HashSet,

C_Sharp

Next, we have used the Remove() function that searches for the name Kriti and removes it from the HashSet.


x.Remove("Kriti")
C_Sharp


And we get the below output,

Output :



  Mohan
  Salim

How to remove all the elements from the HashSet?


The Clear() Method can be used to remove all the elements from the HashSet.


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new HashSet<string>(); 
        
        x.Add("Mohan");
        x.Add("Kriti");
        x.Add("Salim");
        
        x.Clear();
    
        foreach (var i in x)  
        {  
            System.Console.WriteLine(i);  
        }
    }    
}


Output :




So, in the above code we have created a HashSet and initialised to the variable x.


var x = new HashSet<string>();
x.Add("Mohan");
x.Add("Kriti");
x.Add("Salim");

Below is how the values are positioned in the HashSet,

C_Sharp

Next, we have used the Clear() function that removes all the elements from the HashSet making the HashSet empty.


And we get an empty HashSet as output.