Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top