Open In App

C# | Remove all elements from a HashSet

Last Updated : 01 Feb, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Clear Method is used to remove all the elements from a HashSet object.

Syntax:

mySet.Clear(); 

Here, mySet is the name of the HashSet.

Below given are some examples to understand the implementation in a better way:

Example 1:




// C# code to remove all elements from HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of integers
        HashSet<int> mySet = new HashSet<int>();
  
        // Inserting even numbers less than
        // equal to 20 in HashSet mySet1
        for (int i = 0; i < 10; i++) {
            mySet.Add(i * 2);
        }
  
        // Displaying the number of elements in HashSet
        Console.WriteLine(mySet.Count);
  
        // Removing all the elements from HashSet
        mySet.Clear();
  
        // Displaying the number of elements in HashSet
        // after removing all the elements from it
        Console.WriteLine(mySet.Count);
    }
}


Output:

10
0

Example 2:




// C# code to remove all elements from HashSet
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HashSet of strings
        HashSet<string> mySet = new HashSet<string>();
  
        // Inserting elements in HashSet
        mySet.Add("Geeks");
        mySet.Add("and");
        mySet.Add("GeeksforGeeks");
        mySet.Add("are");
        mySet.Add("the");
        mySet.Add("best");
  
        // Displaying the number of elements in HashSet
        Console.WriteLine(mySet.Count);
  
        // Removing all the elements from HashSet
        mySet.Clear();
  
        // Displaying the number of elements in HashSet
        // after removing all the elements from it
        Console.WriteLine(mySet.Count);
  
        // Inserting elements in HashSet
        mySet.Add("Join");
        mySet.Add("Geeks");
        mySet.Add("Classes");
  
        // Displaying the number of elements in HashSet
        Console.WriteLine(mySet.Count);
    }
}


Output:

6
0
3

Reference:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads