【发布时间】:2011-03-11 22:29:21
【问题描述】:
请建议将Dictionary<Key, Value> 转换为Hashset<Value> 的最短方法
IEnumerables 是否有内置的 ToHashset() LINQ 扩展?
提前谢谢你!
【问题讨论】:
标签: c# dictionary hashset
请建议将Dictionary<Key, Value> 转换为Hashset<Value> 的最短方法
IEnumerables 是否有内置的 ToHashset() LINQ 扩展?
提前谢谢你!
【问题讨论】:
标签: c# dictionary hashset
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<TKey>(myDictionary.Keys)。
new HashSet<Value>(YourDict.Values);
【讨论】: