【问题标题】:C#:Conversion of Dictionary<String,String> to Dictionary<String, Dictionary<String,String>>C#:将 Dictionary<String,String> 转换为 Dictionary<String, Dictionary<String,String>>
【发布时间】:2010-10-23 14:03:26
【问题描述】:

第一个Dictionary就像

        Dictionary<String, String> ParentDict = new Dictionary<String, String>();
        ParentDict.Add("A_1", "1");
        ParentDict.Add("A_2", "2");
        ParentDict.Add("B_1", "3");
        ParentDict.Add("B_2", "4"); 
        ParentDict.Add("C_1", "5");

我需要把它转换成一个新的Dictionary&lt;String, Dictionary&lt;String,String&gt;&gt;

结果将包含

Key                    Value

              Key                   Value             
_________________________________________________

"A"             "A_1"                    "1"
                "A_2"                    "2"

"B"             "B_1"                    "1"
                "B_2"                    "2"

"C"             "C_1"                    "1"

现在我正在使用nested for loop 来执行此操作。

我如何使用LNQLAMBDA Expression来做到这一点?

【问题讨论】:

  • 为什么需要这个数据结构?
  • 我问的原因是嵌套字典通常比具有复合键或查找的单深度字典更慢且不太合适。

标签: c# linq dictionary lambda


【解决方案1】:
 var result = ParentDict.GroupBy(p => p.Key[0].ToString())
                        .ToDictionary(g => g.Key, g => g.ToDictionary(x => x.Key, x => x.Value));

【讨论】:

    【解决方案2】:

    试试:

    var result = from p in ParentDict
                 group p by p.Key[0] into g
                 select new { Key = g.Key, Value = g };
    

    这应该为您提供 { Key, Value } 的列表,其中 Key 将是“A”、“B”、“C”等,而 Value 将是来自 ParentDict 的 KeyValuePair 的原始实例。

    您可以在此 MSDN 页面上找到更多 LINQ 示例查询:101 Linq Samples

    【讨论】:

      【解决方案3】:

      我怀疑这样做的原因是因为您需要能够查找特定键字母的所有条目。在这种情况下,Lookup 通常是更好的匹配:

      var letterLookup = ParentDict.ToLookup(kv=>kv.Key[0]);
      

      可以这样使用:

      //letterLookup['A'] is an IEnumerable<KeyValuePair<string,string>>...
      
      Console.WriteLine(string.Join(", ",
              letterLookup['A'].Select(kv=>kv.ToString()).ToArray()
          )); // [A_1, 1], [A_2, 2]
      
      Console.WriteLine(new XElement("root",
              letterLookup['B'].Select(kv=>new XElement(kv.Key,kv.Value))
          ));// <root><B_1>3</B_1><B_2>4</B_2></root>
      
      
      Console.WriteLine(letterLookup['B'].Any()); //true
      Console.WriteLine(letterLookup['Z'].Any()); //false
      

      查找字典的优点是它可以包含任何给定键的多个值(与字典不同),并且如果某个键不存在,它具有一致的 API:然后它返回空的可枚举,而包含枚举的字典可能会抛出 KeyNotFoundException,或者返回 null,或者返回空的枚举,这一切都取决于您如何创建它。

      【讨论】:

      • @Eamon Nerbonne:哦,对不起……这不是原因(我知道lookup)。其实我的要求就是这样......
      • 最后我将数据(以第二个字典的格式)转储到一个xml文件......(xml文件具有第二个字典的结构)
      • 添加了一个带有 XML 输出的示例。
      猜你喜欢
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 2012-07-19
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多