VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-remove-all-elements-in-a-collection-from-a-hashset/

⇱ C# | Remove all elements in a collection from a HashSet - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# | Remove all elements in a collection from a HashSet

Last Updated : 11 Jul, 2025

In C#, you can use the ExceptWith() method to remove all the elements in a collection from a HashSet. The ExceptWith() method removes all the elements in the specified collection from the current HashSet.

Here is an example code that demonstrates how to use the ExceptWith() method to remove all the elements in a collection from a HashSet:


Output
Before removing elements from set1:
1 2 3 4 5 
After removing elements from set1:
1 3 5 

A HashSet is an unordered collection of the unique elements. It is found in 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.ExceptWith(IEnumerable) Method is used to remove all elements in the specified collection from the current HashSet object. Syntax:

mySet2.ExceptWith(mySet1)

Here, mySet1 and mySet2 are the two HashSets and the function returns the elements of mySet2 which are not in mySet1. Exception: This method will give ArgumentNullException if the HashSet is null. Below given are some examples to understand the implementation in a better way: 

Example 1: 

Example 2: 

Comment

Explore