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

lea*_*tes 165 c# collections ienumerable dictionary idictionary

我有一个返回的方法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);
}
Run Code Online (Sandbox Code Playgroud)

呼叫者:

Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey("something");
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 311

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

Dictionary<string, ArrayList> result = target.GetComponents()
                                      .ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)

没有这样的东西,IEnumerable<T1, T2>但是a KeyValuePair<TKey, TValue>很好.

  • 2016年,我仍然不得不谷歌这个.你会认为`Dictionary'会有一个构造函数接受`IEnumerable <KeyValuePair <TKey,TValue >>`就像`List <T>`需要一个`IEnumerable <T>`.此外,没有"AddRange"甚至"添加"来获取键/值对.那是怎么回事? (17认同)
  • 鉴于Dictionary <TKey,TValue>实现了IEnumerable <KeyValuePair <TKey,TValue >>,你会认为会有一个不需要参数的调用,但是哦.很容易制作自己的. (13认同)
  • @DanVerdolino我知道.你会认为这是因为它就像你可能想要用IEnumerable的KVP做的最常见的事情之一. (5认同)
  • 现在是2017年,我们可以添加这个作为扩展方法! (4认同)
  • 通过 [MoreLinq](https://www.nuget.org/packages/morelinq/) 解决了很多“我不敢相信 .net 核心没有 &lt;明显功能&gt;”的问题。包括无参数 IEnumerable&lt;KeyValuePair&gt; -&gt; `ToDictionary()` (2认同)

小智 10

从 .NET Core 2.0 开始,构造函数Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)现在已经存在。