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
| Expected | O(1) for Remove |
|---|---|
| Worst case | O(n) for RemoveWhere (visits every element) |
| Extra space | O(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));
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.