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

ExpectedO(m) for UnionWith and ExceptWith, where m is the size of other; IntersectWith O(n + m) in general
Extra spaceO(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]));
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/HashSetExamples.cs

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.