Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove all elements from a HashSet in C#
To remove all elements from a HashSet in C#, you use the Clear() method. This method removes all elements from the HashSet and resets its count to zero. The Clear() method is the most efficient way to empty a HashSet completely.
Syntax
Following is the syntax for the Clear() method −
hashSet.Clear();
Parameters
The Clear() method takes no parameters.
Return Value
The Clear() method returns void (no return value).
Using Clear() Method
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
set1.Add("E");
set1.Add("F");
set1.Add("G");
set1.Add("H");
Console.WriteLine("Elements in HashSet...");
foreach (string res in set1) {
Console.WriteLine(res);
}
Console.WriteLine("Count of HashSet1 = " + set1.Count);
set1.Clear();
Console.WriteLine("Count of HashSet1 (after Clear) = " + set1.Count);
}
}
The output of the above code is −
Elements in HashSet... A B C D E F G H Count of HashSet1 = 8 Count of HashSet1 (after Clear) = 0
Clearing Multiple HashSets
Example
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
HashSet<string> set1 = new HashSet<string>();
set1.Add("A");
set1.Add("B");
set1.Add("C");
set1.Add("D");
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1) {
Console.WriteLine(res);
}
Console.WriteLine("Elements in HashSet2...");
foreach (string res in set2) {
Console.WriteLine(res);
}
Console.WriteLine("Count of HashSet1 = " + set1.Count);
Console.WriteLine("Count of HashSet2 = " + set2.Count);
set1.Clear();
set2.Clear();
Console.WriteLine("Count of HashSet1 (after Clear) = " + set1.Count);
Console.WriteLine("Count of HashSet2 (after Clear) = " + set2.Count);
}
}
The output of the above code is −
Elements in HashSet1... A B C D Elements in HashSet2... John Jacob Ryan Tom Count of HashSet1 = 4 Count of HashSet2 = 4 Count of HashSet1 (after Clear) = 0 Count of HashSet2 (after Clear) = 0
Comparison with Other Collection Types
| Collection Type | Clear Method | Time Complexity |
|---|---|---|
| HashSet<T> | Clear() | O(n) |
| List<T> | Clear() | O(n) |
| Dictionary<K,V> | Clear() | O(n) |
Conclusion
The Clear() method is the standard and most efficient way to remove all elements from a HashSet in C#. After calling Clear(), the HashSet becomes empty with a count of zero, and you can immediately start adding new elements if needed.
Advertisements
