【问题标题】:How to convert IEnumerable of KeyValuePair<x, y> to Dictionary?如何将 KeyValuePair<x, y> 的 IEnumerable 转换为 Dictionary?
【发布时间】:2011-12-12 14:45:11
【问题描述】:

是否有将KeyValuePair&lt;T, U&gt; 的列表/可编号转换为Dictionary&lt;T, U&gt; 的简化方法?

Linq 转换,.ToDictionary() 扩展不起作用。

【问题讨论】:

标签: c# linq dictionary


【解决方案1】:

与其他类似,但使用new 而不是ToDictionary(因为new 已经支持KeyValuePair 枚举)并允许传递IEqualityComparer&lt;TKey&gt;

为了完整起见,还包括一个ToReadOnlyDictionary 变体。

public static class EnumerableKeyValuePairExtensions {

    public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IEqualityComparer<TKey>? comparer = null)
    where TKey : notnull
        => new Dictionary<TKey, TValue>(keyValuePairs, comparer);

    public static ReadOnlyDictionary<TKey, TValue> ToReadOnlyDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs, IEqualityComparer<TKey>? comparer = null)
    where TKey : notnull
        => new ReadOnlyDictionary<TKey, TValue>(keyValuePairs.ToDictionary(comparer));
}

【讨论】:

    【解决方案2】:

    这是我能做到的最好的:

    public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> keyValuePairs)
    {
        var dict = new Dictionary<TKey, TValue>();
        var dictAsIDictionary = (IDictionary<TKey, TValue>) dict;
        foreach (var property in keyValuePairs)
        {
            (dictAsIDictionary).Add(property);
        }
        return dict;
    }
    

    我比较了使用 Linq.ToDictionary 将 2000 万个键值对的 IEnumerable 转换为 Dictionary 的速度和这个速度。这个在 Linq 版本的 80% 的时间内运行。所以它更快,但不是很多。我认为您确实需要重视这 20% 的节省才能使其值得使用。

    【讨论】:

      【解决方案3】:

      您可以创建自己的扩展方法,并按预期执行。

      public static class KeyValuePairEnumerableExtensions
      {
          public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
          {
              return source.ToDictionary(item => item.Key, item => item.Value);
          }
      }
      

      【讨论】:

        【解决方案4】:
        .ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);
        

        这不是更多的工作吗?

        【讨论】:

        • 遗憾的是没有更清洁的方法,但它会做!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        相关资源
        最近更新 更多