C#:字典值HashSet的转换 [英] C#: Dictionary values to hashset conversion
本文介绍了C#:字典值HashSet的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请,建议最短的办法词典<转换;关键字,值>
到的Hashset<价值>
有内置的 ToHashset() LINQ扩展IEnumerables?
感谢你在前进!
解决方案
VAR yourSet =新的HashSet< TValue>(yourDictionary.Values);
或者,如果你愿意,你可以敲你自己的简单的扩展方法来处理类型推断。然后,你将不再需要明确指定 T
的 HashSet的<的; T>
:
VAR yourSet = yourDictionary.Values.ToHashSet();
// ...
公共静态类EnumerableExtensions
{
公共静态的HashSet< T> ToHashSet< T>(这个IEnumerable的< T>源)
{
返回source.ToHashSet< T>(NULL);
}
公共静态的HashSet< T> ToHashSet< T>(
本的IEnumerable< T>源的IEqualityComparer< T>比较器)
{
如果(来源== NULL)抛出新的ArgumentNullException(源);
返回新的HashSet< T>(源,比较器);
}
}
Please, suggest the shortest way to convert Dictionary<Key, Value>
to Hashset<Value>
Is there built-in ToHashset() LINQ extension for IEnumerables ?
Thank you in advance!
解决方案
var yourSet = new HashSet<TValue>(yourDictionary.Values);
Or, if you prefer, you could knock up your own simple extension method to handle the type inferencing. Then you won't need to explicitly specify the T
of the 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#:字典值HashSet的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文