Is there an AddRange equivalent for a HashSet in C#
With a list you can do:
list.AddRange(otherCollection);
There is no add range method in a HashSet
.
What is the best way to add another ICollection
to a HashSet
?
For HashSet<T>
, the name is UnionWith
.
This is to indicate the distinct way the HashSet
works. You cannot safely Add
a set of random elements to it like in Collections
, some elements may naturally evaporate.
I think that UnionWith
takes its name after "merging with another HashSet
", however, there's an overload for IEnumerable<T>
too.
This is one way:
public static class Extensions
{
public static bool AddRange<T>(this HashSet<T> source, IEnumerable<T> items)
{
bool allAdded = true;
foreach (T item in items)
{
allAdded &= source.Add(item);
}
return allAdded;
}
}
You can also use CONCAT with LINQ. This will append a collection or specifically a HashSet<T>
onto another.
var A = new HashSet<int>() { 1, 2, 3 }; // contents of HashSet 'A'
var B = new HashSet<int>() { 4, 5 }; // contents of HashSet 'B'
// Concat 'B' to 'A'
A = A.Concat(B).ToHashSet(); // Or one could use: ToList(), ToArray(), ...
// 'A' now also includes contents of 'B'
Console.WriteLine(A);
>>>> {1, 2, 3, 4, 5}
NOTE: Concat()
creates an entirely new collection. Also, UnionWith()
is faster than Concat().
"... this (Concat()
) also assumes you actually have access to the variable referencing the hash set and are allowed to modify it, which is not always the case." – @PeterDuniho