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 collection to a HashSet?


For HashSet, the name is UnionWith.

This is to indicate the distinct way the HashSet works. You cannot safely "Add" 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 too :)


这是一种方式:

public static class Extensions
{
    public static bool AddRange<T>(this HashSet<T> @this, IEnumerable<T> items)
    {
        bool allAdded = true;
        foreach (T item in items)
        {
            allAdded &= @this.Add(item);
        }
        return allAdded;
    }
}
链接地址: http://www.djcxy.com/p/53890.html

上一篇: Silverlight中的可观察集合

下一篇: 在C#中有一个HashSet的AddRange等价物吗?