How to remove all elements from the HashSet in C#
The HashSet<T> generic class in the System.Collections.Generic namespace provides the Clear() method, which is used to remove all the elements from a HashSetHashSet<T> becomes empty after the Clear() method is called.
Syntax
public void Clear ();
-
Other object references from elements of the
HashSet<T>are also released after calling theClear()method. -
The HashSet’s
Countproperty becomes after the0 zero Clear()method is called. -
This method does not change the capacity of the HashSet
. -
This method changes the state of the HashSet.
In the example below, we first create a HashSet of strings and add two strings to it: January and February. We then print the count of elements in the HashSet.
Next, we call the Clear() method to remove all elements of the HashSet. We again print the count and observe zero after the Clear() method is called.
The program prints the following output and exits.
Added 'January' and 'February' to HashSet, Count : 2
Count of HashSet afte Clear() : 0
using System;using System.Collections.Generic;class HashSetAdd{static void Main(){HashSet<string> monthSet = new HashSet<string>();monthSet.Add("January");monthSet.Add("February");Console.WriteLine($"Added 'January' and 'February' to HashSet, Count : {monthSet.Count}");monthSet.Clear();Console.WriteLine($"Count of HashSet afte Clear() : {monthSet.Count}");}}