从一个IEnumerable<KeyValuePair<>&gt中重新创建一个字典。

问题描述 投票:171回答:2

我有一个方法,返回一个 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");
c# collections dictionary ienumerable idictionary
2个回答
327
投票

如果你使用的是.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> 是好的。


2
投票

来源(MS docs)

知道这个问题已经有人回答过了,但首先看到这个帖子,然后在文档中找到了解决方案,我想这可能会帮助另一个未来的go-er。

从dot net core 2.0开始,构造函数 Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)现在存在。

© www.soinside.com 2019 - 2024. All rights reserved.