Is there an AddRange equivalent for a HashSet in C#

后端 未结 2 650
南笙
南笙 2021-01-30 12:01

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 anoth

相关标签:
2条回答
  • 2021-01-30 12:47

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-30 12:51

    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.

    0 讨论(0)
提交回复
热议问题