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