简体   繁体   English

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

[英]Is there an AddRange equivalent for a HashSet in C#

With a list you can do:使用列表,您可以执行以下操作:

list.AddRange(otherCollection);

There is no add range method in a HashSet . HashSet没有添加范围方法。 What is the best way to add another ICollection to a HashSet ?将另一个ICollection添加到HashSet的最佳方法是什么?

For HashSet<T> , the name is UnionWith .对于HashSet<T> ,名称是UnionWith

This is to indicate the distinct way the HashSet works.这是为了表明HashSet工作的独特方式。 You cannot safely Add a set of random elements to it like in Collections , some elements may naturally evaporate.您不能像在Collections那样安全地向其中Add一组随机元素,某些元素可能会自然消失。

I think that UnionWith takes its name after "merging with another HashSet ", however, there's an overload for IEnumerable<T> too.我认为UnionWith在“与另一个HashSet合并”之后得名,但是, IEnumerable<T>也有重载。

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

You can also use CONCAT with LINQ.您还可以将CONCAT与 LINQ 一起使用。 This will append a collection or specifically a HashSet<T> onto another.这会将一个集合或特别是一个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}

NOTE: Concat() creates an entirely new collection.注意: Concat()创建一个全新的集合。 Also, UnionWith() is faster than Concat().此外, UnionWith()比 Concat() 快。

" ... this ( Concat() ) also assumes you actually have access to the variable referencing the hash set and are allowed to modify it, which is not always the case. " – @PeterDuniho ...这个( Concat() )还假设您实际上可以访问引用散列集的变量并允许修改它,但情况并非总是如此。 ” – @PeterDuniho

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM