C# 中的 HashSet 是否有等效的 AddRange

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15267034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:10:50  来源:igfitidea点击:

Is there an AddRange equivalent for a HashSet in C#

c#collectionshashsetaddrange

提问by Stefanos Kargas

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?

HashSet 中没有添加范围方法。将另一个集合添加到 HashSet 的最佳方法是什么?

采纳答案by quetzalcoatl

For HashSet<T>, the name is UnionWith.

对于HashSet<T>,名称是UnionWith

This is to indicate the distinct way the HashSetworks. You cannot safely Adda set of random elements to it like in Collections, some elements may naturally evaporate.

这是为了表明不同的HashSet工作方式。你不能Add像 in那样安全地使用一组随机元素Collections,有些元素可能会自然蒸发。

I think that UnionWithtakes its name after "merging with another HashSet", however, there's an overload for IEnumerable<T>too.

我认为UnionWith它的名字来源于“与另一个合并HashSet”,但是,它也有一个过载IEnumerable<T>

回答by RoadieRich

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