简体   繁体   English

C#:字典值到hashset转换

[英]C#: Dictionary values to hashset conversion

Please, suggest the shortest way to convert Dictionary<Key, Value> to Hashset<Value> 请建议将Dictionary<Key, Value>转换为Hashset<Value>的最短路径

Is there built-in ToHashset() LINQ extension for IEnumerables ? IEnumerables是否内置ToHashset() LINQ扩展?

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> : 然后你不需要显式指定HashSet<T>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);
    }
}

new HashSet<Value>(YourDict.Values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM