398

使用列表,您可以:

list.AddRange(otherCollection);

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

4

3 回答 3

706

因为HashSet<T>,名字是UnionWith

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

我认为UnionWith它在“与另一个合并HashSet”之后得名,但是,也有一个重载IEnumerable<T>

于 2013-03-07T09:12:08.677 回答
8

这是一种方式:

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;
    }
}
于 2013-03-07T09:17:50.767 回答
5

您还可以将CONCAT与 LINQ 一起使用。这会将一个集合或特别是一个附加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() 更快。

... this ( Concat()) 还假设您实际上可以访问引用哈希集的变量并允许修改它,但情况并非总是如此。 ” – @PeterDuniho

于 2021-06-22T23:50:58.977 回答