代码之家  ›  专栏  ›  技术社区  ›  Andrew Florko

C:字典值到哈希集的转换

  •  8
  • Andrew Florko  · 技术社区  · 14 年前

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

    有内置的吗 托哈塞特() IEnumerables的LINQ扩展?

    提前谢谢!

    2 回复  |  直到 9 年前
        1
  •  13
  •   LukeH    9 年前
    var yourSet = new HashSet<TValue>(yourDictionary.Values);
    

    或者,如果您愿意,您可以使用自己的简单扩展方法来处理类型推断。那么您就不需要显式地指定 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);
        }
    }
    
        2
  •  5
  •   Donnie    14 年前

    new HashSet<Value>(YourDict.Values);