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
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); } } }
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,
Next, we have used the Remove() function that searches for the name Kriti and removes it from the HashSet.
x.Remove("Kriti")
And we get the below output,
The Clear() Method can be used to remove all the elements from the HashSet.
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); } } }
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,
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.