从 IEnumerable<KeyValuePair<>> 重新创建字典 [英] Recreating a Dictionary from an IEnumerable<KeyValuePair<>>
本文介绍了从 IEnumerable<KeyValuePair<>> 重新创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回 IEnumerable
的方法,但是一些调用者要求该方法的结果是一个字典.如何将 IEnumerable
转换为 Dictionary
以便我可以使用 TryGetValue
?
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
?
方法:
public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
来电者:
Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
推荐答案
如果您使用的是 .NET 3.5 或 .NET 4,使用 LINQ 创建字典很容易:
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);
没有 IEnumerable
这样的东西,但是 KeyValuePair
很好.
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
这篇关于从 IEnumerable<KeyValuePair<>> 重新创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文