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:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet = new HashSet< int >();
for ( int i = 0; i < 10; i++) {
mySet.Add(i * 2);
}
Console.WriteLine(mySet.Count);
mySet.Clear();
Console.WriteLine(mySet.Count);
}
}
|
Example 2:
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< string > mySet = new HashSet< string >();
mySet.Add( "Geeks" );
mySet.Add( "and" );
mySet.Add( "GeeksforGeeks" );
mySet.Add( "are" );
mySet.Add( "the" );
mySet.Add( "best" );
Console.WriteLine(mySet.Count);
mySet.Clear();
Console.WriteLine(mySet.Count);
mySet.Add( "Join" );
mySet.Add( "Geeks" );
mySet.Add( "Classes" );
Console.WriteLine(mySet.Count);
}
}
|
Reference: