C#: Dictionary values to hashset conversion

旧街凉风 提交于 2020-01-24 02:49:08

问题


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!


回答1:


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



回答2:


new HashSet<Value>(YourDict.Values);



来源:https://stackoverflow.com/questions/3180030/c-dictionary-values-to-hashset-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!