您可以使用列表:
list.AddRange(otherCollection);
HashSet 中没有添加范围方法。 将另一个集合添加到HashSet的最佳方法是什么?
答案 0 :(得分:423)
对于HashSet<T>
,名称为UnionWith
。
这是为了表明HashSet
的独特方式。你不能像Add
那样安全Collections
一组随机元素,有些元素可能会自然消失。
我认为UnionWith
在“与另一个HashSet
合并”之后取名,但是,IEnumerable<T>
也会出现过载。
答案 1 :(得分:4)
这是一种方式:
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;
}
}
答案 2 :(得分:0)
您也可以在 LINQ 中使用 CONCAT。这会将一个集合或特别是一个 HashSet<T>
附加到另一个集合上。
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}
注意: Concat()
创建一个全新的集合。此外,UnionWith()
比 Concat() 快。
“...此 (Concat()
) 还假设您实际上有权访问引用散列集的变量并允许对其进行修改,但情况并非总是如此。” – @PeterDuniho