【问题标题】:Merging 3 dictionaries into single dictionary将 3 个字典合并为单个字典
【发布时间】:2011-05-04 00:20:09
【问题描述】:
I have the following 

Dictionary<string,string> dict1 has 3 items
"A"="1.1"
"B"="2.1"
"C"="3.1"

Dictionary<string,string> dict2 has 3 items
"A"="1.2"
"B"="2.2"
"C"="3.2"

Dictionary<string,string> dict2 has 3 items
"A"="1.3"
"B"="2.3"
"C"="3.3"

I want a final Dict dictFinal which is of type Dictionary<string,string[]>

"A"="1.1,1.2,1.3"
"B"="2.1,2.2,2.3"
"C"="3.1,3.2,3.3"

【问题讨论】:

    标签: c# generics dictionary merge


    【解决方案1】:

    给定相似的键,提供所有字典的集合并使用SelectMany 处理动态数量的数组项:

    var dictionaries = new[] { dict1, dict2, dict3 };
    var result = dictionaries.SelectMany(dict => dict)
                             .GroupBy(o => o.Key)
                             .ToDictionary(g => g.Key,
                                           g => g.Select(o => o.Value).ToArray());
    

    dictionaries 类型可以是List&lt;T&gt;,不一定是上面的数组。重要的是您将它们组合在一个集合中以便对它们进行 LINQ。

    【讨论】:

      【解决方案2】:

      假设所有 3 个字典都有相同的键,以下应该可以完成工作:

      var d1 = new Dictionary<string, string>()
                   {
                       {"A", "1.1"},
                       {"B", "2.1"},
                       {"C", "3.1"}
                   };
      var d2 = new Dictionary<string, string>()
                   {
                       {"A", "1.2"},
                       {"B", "2.2"},
                       {"C", "3.2"}
                   };
      
      var d3 = new Dictionary<string, string>()
                   {
                       {"A", "1.3"},
                       {"B", "2.3"},
                       {"C", "3.3"}
                   };
      
      var result = d1.Keys.ToDictionary(k => k, v => new[] {d1[v], d2[v], d3[v]});
      

      【讨论】:

      • 如果我的数组是动态的,如何在运行时添加新的 d(x)[v]...!
      • @chugh97:查看我对处理动态数组的回复。
      【解决方案3】:

      假设所有人都有相同的键,最直接的方法是:

      Dictionary<string,string[]> result = new Dictionary<string,string[]>();
      foreach(var key in dict1.Keys)
      {
          result[key] = new string[]{dict1[key], dict2[key], dict3[key]}; 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-13
        • 2011-03-30
        • 2017-01-04
        • 2017-07-23
        • 2019-05-16
        • 2018-04-16
        • 1970-01-01
        相关资源
        最近更新 更多