質問

私はこのような何かを行うことができますので、HashSetのための拡張メソッドAddRangeを作成しようとしています:

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

これは私がこれまで持っているものです

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

問題は、私はAddRangeを使用しようとすると、私はこのコンパイラエラーを取得しています:

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.

他の言葉では、私が代わりにこれを使用して終了する必要があります:

hashset.AddRange<Item>(list);

私はここで間違っているのでしょうか?

役に立ちましたか?

解決

あなたのコードは私のために罰金を動作します:

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);
    }
}
あなたはコンパイルに失敗したと同様の短いが、完全なプログラムを与えてもらえますか?

他のヒント

使用

hashSet.UnionWith<Item>(list);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top