9

Dictionary<Key, Value>に変換する最短の方法を提案してくださいHashset<Value>

IEnumerables用の組み込みのToHashset() LINQ拡張機能はありますか?

前もって感謝します!

4

2 に答える 2

14
var yourSet = new HashSet<TValue>(yourDictionary.Values);

または、必要に応じて、型推論を処理するための独自の単純な拡張メソッドをノックアップすることもできます。Tその場合、HashSet<T>:のを明示的に指定する必要はありません。

var yourSet = yourDictionary.Values.ToHashSet();

// ...

public static class EnumerableExtensions
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return source.ToHashSet<T>(null);
    }

    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source, IEqualityComparer<T> comparer)
    {
        if (source == null) throw new ArgumentNullException("source");

        return new HashSet<T>(source, comparer);
    }
}
于 2010-07-05T14:00:33.620 に答える
5

new HashSet<Value>(YourDict.Values);

于 2010-07-05T14:01:41.387 に答える