9

请建议转换Dictionary<Key, Value>为的最短方法Hashset<Value>

IEnumerables是否有内置的ToHashset() LINQ 扩展?

先感谢您!

4

2 回答 2

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

Or, if you prefer, you could knock up your own simple extension method to handle the type inferencing. Then you won't need to explicitly specify the T of the 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 回答