从IEnumerable<KeyValuePair<>>重新创建一个字典

218
我有一个方法返回一个 IEnumerable<KeyValuePair<string, ArrayList>>,但一些调用方需要将方法的结果转换为字典。我该如何将 IEnumerable<KeyValuePair<string, ArrayList>> 转换为 Dictionary<string, ArrayList> 以便可以使用 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");

可能是重复的问题?https://dev59.com/RWsz5IYBdhLWcg3wg4Gv - Coolkau
2个回答

380

如果您使用的是.NET 3.5或.NET 4,则可以使用LINQ轻松创建字典:

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);

并没有 IEnumerable<T1, T2> 这样的类型,但 KeyValuePair<TKey, TValue> 是可以的。


18
考虑到Dictionary<TKey, TValue>实现了IEnumerable<KeyValuePair<TKey, TValue>>,你可能会认为有一个不需要参数的调用方法,但是没关系,自己写一个也很容易。 - Casey
6
我知道。你会认为这是对一个KVPs的IEnumerable最常见的操作之一。 - Casey
22
到了2016年,我还是得通过谷歌搜索才能找到这个。你会想,就像List<T>可以使用IEnumerable<T>构造函数一样,Dictionary也应该有一个接受IEnumerable<KeyValuePair<TKey, TValue>>的构造函数。另外,它甚至没有接受键值对的AddRange或者Add方法。这是怎么回事呢? - mausworks
6
现在是2017年,我们可以将其作为扩展方法添加! - Chris Bush
3
许多人会说“我无法相信.NET Core没有<显而易见的功能>”,这个问题可以通过MoreLinq解决。包括一个无参数的IEnumerable<KeyValuePair> -> ToDictionary()函数。 - aaaaaa
显示剩余2条评论

31

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接