Question

Je suis en train de créer la méthode d'extension AddRange pour HashSet pour que je puisse faire quelque chose comme ceci:

var list = new List<Item>{ new Item(), new Item(), new Item() };
var hashset = new HashSet<Item>();
hashset.AddRange(list);

est ce que j'ai jusqu'à présent:

public static void AddRange<T>(this ICollection<T> collection, List<T> list)
{
    foreach (var item in list)
    {
        collection.Add(item);
    }
}

Le problème est, lorsque je tente d'utiliser AddRange, je reçois cette erreur du compilateur:

The type arguments for method 'AddRange<T>(System.Collections.Generic.ICollection<T>, System.Collections.Generic.List<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

En d'autres termes, je dois finir par utiliser ceci:

hashset.AddRange<Item>(list);

Qu'est-ce que je fais mal ici?

Était-ce utile?

La solution

Votre code fonctionne bien pour moi:

using System.Collections.Generic;

static class Extensions
{
    public static void AddRange<T>(this ICollection<T> collection, List<T> list)
    {
        foreach (var item in list)
        {
            collection.Add(item);
        }
    }
}

class Item {}

class Test
{
    static void Main()
    {
        var list = new List<Item>{ new Item(), new Item(), new Item() };
        var hashset = new HashSet<Item>();
        hashset.AddRange(list);
    }
}

Pourriez-vous donner un programme court mais complet similaire qui ne parvient pas à compiler?

Autres conseils

Utilisez

hashSet.UnionWith<Item>(list);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top