KeyValuePair&LT;从IEnumerable&LT再造一个字典&GT;&GT; [英] Recreating a Dictionary from an IEnumerable<KeyValuePair<>>
问题描述
我有一个返回值的IEnumerable℃的方法; KeyValuePair&LT;字符串,ArrayList的&GT;&GT;
,但一些求助者的需要方法的结果是一个字典。我怎么能转换的IEnumerable&LT; KeyValuePair&LT;字符串,ArrayList的&GT;&GT;
到词典&LT;字符串,ArrayList的&GT;
等等我可以使用 TryGetValue
?
方法:
公开的IEnumerable&LT; KeyValuePair&LT;字符串,ArrayList的&GT;&GT; GetComponents()
{
// ...
产量返回新KeyValuePair&LT;字符串,ArrayList的&GT;(t.Name,controlInformation);
}
来电者:
词典&LT;字符串,ArrayList的&GT;实际= target.GetComponents();
actual.ContainsKey(东西);
如果您正在使用.NET 3.5或.NET 4,可以很容易地创建一个使用LINQ的字典:
词典&LT;字符串,ArrayList的&GT;结果= target.GetComponents()
.ToDictionary(X =&GT; x.Key中,x =&GT; x.Value);
有作为一个的IEnumerable&LT没有这样的事; T1,T2&GT;
但 KeyValuePair&LT; TKEY的,TValue&GT;
是罚款。
I have a method that returns an IEnumerable<KeyValuePair<string, ArrayList>>
, but some of the callers require the result of the method to be a dictionary. How can I convert the IEnumerable<KeyValuePair<string, ArrayList>>
into a Dictionary<string, ArrayList>
so that I can use TryGetValue
?
method:
public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
caller:
Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
这篇关于KeyValuePair&LT;从IEnumerable&LT再造一个字典&GT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!