请建议将
是否有内置的ToHashset() LINQ扩展可以用于IEnumerables?
提前感谢您!
Dictionary<Key, Value>
转换为 Hashset<Value>
的最短途径。是否有内置的ToHashset() LINQ扩展可以用于IEnumerables?
提前感谢您!
Dictionary<Key, Value>
转换为 Hashset<Value>
的最短途径。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);
}
}
new HashSet<Value>(YourDict.Values);
new HashSet<TKey>(myDictionary.Keys)
。 - Riegardt Steyn