The HashSet<T>
generic class in the System.Collections.Generic
ExceptWith()
method.
We use the ExceptWith()
method to remove all elements from the HashSet<T>
present in the specified
public void ExceptWith (System.Collections.Generic.IEnumerable<T> other);
This method takes an IEnumerable<T>
collection as input, and removes all elements from the HashSet<T>
present in the collection of elements.
The ExceptWith()
method represents the mathematical set subtraction operation.
It is an O(n) operation where n
is the number of elements of the passed collection of elements.
The method throws an exception if the input collection is null
.
This method changes the state of the HashSet<T>
.
In the example below, we created a HashSet
of integers and added a few numbers. We also created a new List
of integers and added some elements to it.
using System;using System.Collections.Generic;class HashSetRemover{static void Main(){HashSet<int> numSet = new HashSet<int>();numSet.Add(1);numSet.Add(5);numSet.Add(9);numSet.Add(11);numSet.Add(15);numSet.Add(6);Console.Write("HashSet Elements : ");PrintSet(numSet);List<int> otherList = new List<int>{9,11};Console.WriteLine("Input Collection : {0}", string.Join(" ", otherList.ToArray()));numSet.ExceptWith(otherList);Console.Write("HashSet Elements After ExceptWith() : ");PrintSet(numSet);}private static void PrintSet(HashSet<int> set){Console.Write("{");foreach (int i in set) {Console.Write(" {0}", i);}Console.WriteLine(" }");}}
We call ExceptWith()
with the list of integers as input. This removes all the elements from the HashSet
present in the input list of integers.
The list
contains two elements, 9
and 11
, which were removed from the HashSet
.
We print
the elements of the HashSet
before and after the ExceptWith()
operation. The program prints
the following output and exits.
HashSet Elements : { 1 5 9 11 15 6 }
Input Collection : 9 11
HashSet Elements After ExceptWith() : { 1 5 15 6 }