Efficient Set Difference in C# with `HashSet.ExceptWith()`

Learn how to efficiently perform set difference operations in C# using the `HashSet.ExceptWith()` method. This tutorial explains the functionality, demonstrates its usage with examples, and highlights its efficiency for removing elements from a `HashSet` that are present in another collection.



Using C#'s `HashSet.ExceptWith()` Method for Set Difference

The C# `HashSet.ExceptWith()` method modifies a `HashSet` by removing any elements that are also present in another collection. This operation is analogous to set difference in mathematics (A - B).

Understanding `HashSet.ExceptWith()`

The `ExceptWith()` method efficiently removes elements from the current `HashSet` that are also found in another collection (specified as the argument to `ExceptWith()`). The original `HashSet` is modified; a new `HashSet` is not created. The time complexity of this operation is O(n), where n is the number of elements in the other collection.

`HashSet.ExceptWith()` Syntax


public void ExceptWith(IEnumerable<T> other);

The method takes an `IEnumerable` (like a list or array) as input. The elements in this collection are removed from the current `HashSet` if present.

Example 1: Removing Elements from a HashSet


HashSet<string> set1 = new HashSet<string> { "apple", "banana", "orange", "grape" };
HashSet<string> set2 = new HashSet<string> { "banana", "grape" };
set1.ExceptWith(set2); //Removes "banana" and "grape" from set1.
// ... (code to print set1) ...

Example 2: Real-World Scenario (Science Fair)


HashSet<string> allStudents = new HashSet<string> { ... };
HashSet<string> prizeWinners = new HashSet<string> { ... };
allStudents.ExceptWith(prizeWinners); //Finds students who attended but didn't win.
// ... (code to print the list of students who attended but didn't win) ...

Example 3: Using a List


HashSet<string> mySet = new HashSet<string> { "apple", "banana", "orange" };
List<string> itemsToRemove = new List<string> { "banana", "grape" };
mySet.ExceptWith(itemsToRemove); //Removes "banana" from mySet.
// ... (code to print the updated mySet) ...