Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -907,5 +907,49 @@ static void TestComparerSerialization<TCompared>(IEqualityComparer<TCompared> eq
}

#endregion

#region UnionWith

public static IEnumerable<object[]> UnionWith_HashSet_TestData()
{
foreach (int count in new[] { 0, 1, 75 })
{
foreach (bool destinationEmpty in new[] { true, false })
{
foreach (bool sourceSparseFilled in new[] { true, false })
{
yield return new object[] { count, destinationEmpty, sourceSparseFilled };
}
}
}
}

[Theory]
[MemberData(nameof(UnionWith_HashSet_TestData))]
public void HashSet_Generic_UnionWith_HashSet(int count, bool destinationEmpty, bool sourceSparseFilled)
{
HashSet<T> source = (HashSet<T>)CreateEnumerable(EnumerableType.HashSet, null, count, 0, 0);

if (sourceSparseFilled)
{
List<T> sourceElements = source.ToList();
foreach (int i in NonSquares(count))
source.Remove(sourceElements[i]);
}

HashSet<T> destination = destinationEmpty
? new HashSet<T>(source.Comparer)
: (HashSet<T>)GenericISetFactory(1);

HashSet<T> expected = new HashSet<T>(destination, source.Comparer);
foreach (T item in source)
expected.Add(item);

destination.UnionWith(source);

Assert.True(expected.SetEquals(destination));
}

#endregion
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,14 @@ public void UnionWith(IEnumerable<T> other)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.other);
}

// If this set is empty and other is a HashSet with the same effective comparer,
// we can copy the data directly instead of adding each element individually.
if (Count == 0 && other is HashSet<T> otherAsSet && EffectiveEqualityComparersAreEqual(this, otherAsSet))
{
ConstructFrom(otherAsSet);
return;
}

foreach (T item in other)
{
AddIfNotPresent(item, out _);
Expand Down
Loading