HashSet<T> · C#
UnionWith / IntersectWith / ExceptWith
In-place set algebra against any sequence.
public void UnionWith(IEnumerable<T> other); public void IntersectWith(IEnumerable<T> other); public void ExceptWith(IEnumerable<T> other)
Complexity
| Expected | O(m) for UnionWith and ExceptWith, where m is the size of other; IntersectWith O(n + m) in general |
|---|---|
| Extra space | O(1) for UnionWith/ExceptWith; IntersectWith may allocate O(m) when other is not a compatible set |
Assumes: Good hash distribution.
Each element of other costs one expected O(1) lookup or insert. IntersectWith also has to drop elements of this set that other lacks.
Tested example
var a = new HashSet<int> { 1, 2, 3 };
a.UnionWith([3, 4]); // modifies a in place
Assert.True(a.SetEquals([1, 2, 3, 4]));
a.IntersectWith([2, 4, 6]);
Assert.True(a.SetEquals([2, 4]));
a.ExceptWith([4]);
Assert.True(a.SetEquals([2]));
Parameters
- other
- Any sequence; duplicates in it are ignored.
Behaviour
- Returns
- Nothing; the set itself changes.
- Errors and preconditions
- ArgumentNullException if other is null.
- Changes
- Adds or removes elements of this set.
- Memory and invalidation
- UnionWith may resize. Invalidates enumerators.