¿Hay un equivalente de AddRange para un HashSet en C#


Con una lista puedes hacer:

list.AddRange(otherCollection);

No hay ningún método add range en un HashSet . ¿Cuál es la mejor manera de añadir otra colección a un HashSet?

Author: Stefanos Kargas, 2013-03-07

2 answers

Para HashSet<T>, el nombre es UnionWith.

Esto es para indicar la manera distinta en que funciona el HashSet. No se puede con seguridad Add un conjunto de elementos aleatorios como en Collections, algunos elementos pueden evaporarse naturalmente.

Creo que UnionWith toma su nombre después de "fusionarse con otro HashSet", sin embargo, hay una sobrecarga para IEnumerable<T> también.

 357
Author: quetzalcoatl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 00:08:33

Esta es una manera:

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
Author: RoadieRich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 08:12:39