C#: 将字典的值转换为哈希集合

10
请建议将 Dictionary<Key, Value> 转换为 Hashset<Value> 的最短途径。
是否有内置的ToHashset() LINQ扩展可以用于IEnumerables?
提前感谢您!
2个回答

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

或者,如果你愿意,你可以编写自己的简单扩展方法来处理类型推断。这样你就不需要明确指定HashSet<T>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);
    }
}

3
这个问题和答案对我来说没有意义。根据MSDN的说法,HashSet不能包含重复元素,并且应该被视为一个没有值的Dictionary<TKey,TValue>集合。对我来说,从字典中获取所有的值并将它们分配给HashSet是没有意义的。 - Christopher Painter
不幸的是,KeyCollection对象与HashSet对象并不相同,尽管我多么希望它们是相同的。 - Paul
考虑到这个问题已经有5年历史了,我同意@ChristopherPainter的观点。这有什么意义呢?就唯一性而言,更有意义的是(虽然不是这个特定问题的答案):new HashSet<TKey>(myDictionary.Keys) - Riegardt Steyn

5

new HashSet<Value>(YourDict.Values);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接