请建议最短的转换方式Dictionary<Key, Value>
至 Hashset<Value>
是否有用于 IEnumerables 的内置 ToHashset() LINQ 扩展?
提前致谢!
最佳答案
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);
}
}
关于C#:字典值到哈希集的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3180030/