HashSet<T> · C#

Remove / RemoveWhere

Removes one element, or every element matching a predicate.

public bool Remove(T item); public int RemoveWhere(Predicate<T> match)

Complexity

ExpectedO(1) for Remove
Worst caseO(n) for RemoveWhere (visits every element)
Extra spaceO(1)

Remove finds one bucket; RemoveWhere must test every element.

Tested example

var set = new HashSet<int> { 1, 2, 3 };
Assert.True(set.Remove(2));
Assert.False(set.Remove(2));
Assert.Equal(1, set.RemoveWhere(x => x > 2));
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/HashSetExamples.cs

Parameters

item / match
The element or the condition.

Behaviour

Returns
Remove: whether it was present. RemoveWhere: how many were removed.
Errors and preconditions
RemoveWhere: ArgumentNullException for a null predicate.
Changes
Removes entries.
Memory and invalidation
Does not shrink.