使用列表可以做到:
list.AddRange(otherCollection);
HashSet
中没有添加范围的方法。
最好的方法是如何将另一个 ICollection
添加到 HashSet
中?
使用列表可以做到:
list.AddRange(otherCollection);
HashSet
中没有添加范围的方法。
最好的方法是如何将另一个 ICollection
添加到 HashSet
中?
HashSet<T>
,名称为UnionWith
。HashSet
的独特工作方式。您不能像在Collections
中那样安全地将一组随机元素添加到其中,因为某些元素可能会自然蒸发。UnionWith
的命名来自“与另一个HashSet
合并”,但是也有一个IEnumerable<T>
的重载。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;
}
}
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() 更快。
"...这也假设您实际上可以访问引用哈希集的变量并被允许修改它,但这并不总是情况。"- @PeterDuniho
Concat()
。但这样做比调用专门为此目的设计的UnionWith()
方法要差100%,正如所提供的答案建议的那样。请注意,这也假定您实际上可以访问引用哈希集的变量并且被允许修改它,这并不总是情况。 - Peter DunihoHashSet<T>
),并且必须从头开始填充第三个对象,而调用Add()
迭代地创建没有新对象,只需要添加实际上是新的元素。我怀疑你的建议比内置的UnionWith()
方法或其他答案中提出的扩展方法更高效。 - Peter DunihoAddRange()
。问题明确要求将另一个ICollection
添加到HashSet
中,然而你提出的解决方案根本没有做到这一点;相反,它创建了一个全新的HashSet<T>
。 - Peter Duniho
HashSet
(和ISet
)是以数学集合术语创建的。UnionWith
是较接近的术语。除了Except
外,从数学角度讲,显然应该将其命名为Subtract
。 - fa wildchild