Is there an AddRange equivalent for a HashSet in C#

女生的网名这么多〃 提交于 2019-12-20 08:52:32

问题


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?


回答1:


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.




回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/15267034/is-there-an-addrange-equivalent-for-a-hashset-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!