【问题标题】:Recreating a Dictionary from an IEnumerable<KeyValuePair<>>从 IEnumerable<KeyValuePair<>> 重新创建字典
【发布时间】:2011-02-07 20:38:03
【问题描述】:

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


【解决方案1】:

从 .NET Core 2.0 开始,构造函数 Dictionary&lt;TKey,TValue&gt;(IEnumerable&lt;KeyValuePair&lt;TKey,TValue&gt;&gt;) 现在存在。

【讨论】:

    【解决方案2】:

    如果您使用的是 .NET 3.5 或 .NET 4,使用 LINQ 创建字典很容易:

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

    没有IEnumerable&lt;T1, T2&gt; 这样的东西,但KeyValuePair&lt;TKey, TValue&gt; 很好。

    【讨论】:

    • 你会认为会有一个不需要参数的调用,因为 Dictionary 实现了 IEnumerable>,但是哦,好吧。很容易自己制作。
    • @DanVerdolino 我知道。您可能会这样认为,因为这可能是您可能想要对 KVP 的 IEnumerable 执行的最常见的事情之一。
    • 2016 年了,我还是得用谷歌搜索一下。你会认为Dictionary 的构造函数会使用IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;,就像List&lt;T&gt; 使用IEnumerable&lt;T&gt; 一样。也没有采用键/值对的AddRange 甚至Add。那是怎么回事?
    • 现在是 2017 年,我们可以将其添加为扩展方法!
    • 很多“我不敢相信.net core没有”通过MoreLinq解决。包括一个无参数的 IEnumerable -> ToDictionary()
    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多