C#:Dictionary<String,String> 到 Dictionary<String, Dictionary<String,String>> 的转换

标签 c# linq dictionary lambda

第一个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<String, Dictionary<String,String>>

结果将包含

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做这个。

我如何使用 LNQ 执行此操作?或 LAMBDA Expression

最佳答案

 var result = ParentDict.GroupBy(p => p.Key[0].ToString())
                        .ToDictionary(g => g.Key, g => g.ToDictionary(x => x.Key, x => x.Value));

关于C#:Dictionary<String,String> 到 Dictionary<String, Dictionary<String,String>> 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004348/

相关文章:

c# - 加速插入 - 一次插入列表

c# - 如何将变量用作类型?

python - 无法更新词典

c++ - 如果没有明确的 < 运算符,std::less 如何工作?

python - 如何将新的键值对添加到字典中,其中值是数组的数组

c# - UDP打洞: testability on single machine

c# - Protocol Buffer#3 将消息从 c++ 发送到 c#

linq - IEnumerable<T>.Count() 与 List<T>.Count 与 Entity Framework

c# - LINQ 查询中的 NullReferenceException

c# - 根据属性值在 C# 中查找函数