【问题标题】:C#: Dictionary values to hashset conversionC#:字典值到哈希集的转换
【发布时间】:2011-03-11 22:29:21
【问题描述】:

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

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

提前谢谢你!

【问题讨论】:

    标签: c# dictionary hashset


    【解决方案1】:
    var yourSet = new HashSet<TValue>(yourDictionary.Values);
    

    或者,如果您愿意,您可以使用自己的简单扩展方法来处理类型推断。那么您就不需要明确指定HashSet&lt;T&gt;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);
        }
    }
    

    【讨论】:

    • 这个问题和答案对我来说没有意义。根据 MSDN,HashSet 不能包含重复元素,应将其视为没有值的 Dictionary 集合。从 Dictionary 中获取所有值并将它们分配给我的 HashSet 是没有意义的。
    • 不幸的是,KeyCollection 对象与 HashSet 对象不同,尽管我多么希望它是如此。
    • 记住这个问题已经有 5 年历史了;我同意@ChristopherPainter。重点是什么?就唯一性而言,更有意义的是(尽管不是这个特定问题的答案):new HashSet&lt;TKey&gt;(myDictionary.Keys)
    【解决方案2】:

    new HashSet&lt;Value&gt;(YourDict.Values);

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2015-02-12
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多