C# | Remove elements from a HashSet with conditions defined by the predicate
A HashSet is an unordered collection of the unique elements. It comes under 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<T>.RemoveWhere(Predicate<T>) method is used to remove all elements that match the conditions defined by the specified predicate from a HashSet<T> collection.
public int RemoveWhere (Predicate<T> match);
Return Value: This method returns the number of elements that were removed from the HashSet<T> collection.
Exception: This method will give the ArgumentNullException if the match is null.
Note: Calling this method is an O(n) operation, where n is Count i.e, the number of elements that are contained in the set.
Below are the programs to illustrate the use of HashSet<T>.RemoveWhere(Predicate<T>) Method:
The elements in HashSet are : 0 1 2 3 4 5 6 7 8 9 Number of elements are : 10 The elements in HashSet are : 1 3 5 7 9 Number of elements are : 5
Number of elements are : 20 Number of elements are : 16