KeyValuePair<从IEnumerable&LT再造一个字典>> [英] Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

查看:272
本文介绍了KeyValuePair<从IEnumerable&LT再造一个字典>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回值的IEnumerable℃的方法; KeyValuePair<字符串,ArrayList的>> ,但一些求助者的需要方法的结果是一个字典。我怎么能转换的IEnumerable< KeyValuePair<字符串,ArrayList的>> 词典<字符串,ArrayList的> 等等我可以使用 TryGetValue

方法:

 公开的IEnumerable< KeyValuePair<字符串,ArrayList的>> GetComponents()
{
  // ...
  产量返回新KeyValuePair<字符串,ArrayList的>(t.Name,controlInformation);
}

来电者:

 词典<字符串,ArrayList的>实际= target.GetComponents();
actual.ContainsKey(东西);


解决方案

如果您正在使用.NET 3.5或.NET 4,可以很容易地创建一个使用LINQ的字典:

 词典<字符串,ArrayList的>结果= target.GetComponents()
                                      .ToDictionary(X => x.Key中,x => x.Value);

有作为一个的IEnumerable&LT没有这样的事; T1,T2> KeyValuePair< TKEY的,TValue> 是罚款。

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆