C#:字典值到hashset转换

And*_*rko 8 c# dictionary hashset

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

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

先感谢您!

Luk*_*keH 13

var yourSet = new HashSet<TValue>(yourDictionary.Values);
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意,可以使用自己的简单扩展方法来处理类型推理.然后,你将不再需要显式地指定THashSet<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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个问题和答案对我来说没有意义.根据MSDN,HashSet不能包含重复元素,应该被认为是没有值的Dictionary <TKey,TValue>集合.从Dictionary中获取所有值并将它们分配给HashSet对我来说没有意义. (3认同)

Don*_*nie 5

new HashSet<Value>(YourDict.Values);