开发者

C#: Dictionary values to hashset conversion

Please, 开发者_开发知识库suggest the shortest way to convert Dictionary<Key, Value> to Hashset<Value>

Is there built-in ToHashset() LINQ extension for IEnumerables ?

Thank you in advance!


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);
    }
}


new HashSet<Value>(YourDict.Values);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜