DataTable to Dictionary <string,dictionary <string,=“”dictionary <string,string =“”>&gt;&gt; </string,>

时间:2013-10-02 13:40:05

标签: c# linq dictionary

我有一个包含4列的DataTable -

ParentDictionary,Id,Key和Value。

目前我有以下代码 -

var dict = t.Tables[0].AsEnumerable().
            GroupBy(row => row.Field<string>("ParentId")).ToDictionary(
                    g => g.Key,
                    g => g.ToDictionary(row => row.Field<string>("Key"), row => row.Field<string>("Value"))
        );

是否有人有解决方案将此表格转换为

Dictionary<string, Dictionary<string, Dictionary<string,string>>>

1 个答案:

答案 0 :(得分:0)

你可以做那样的事情

var heckOfAnObject = dataTable
            .AsEnumerable()
            .GroupBy(m => m.Field<string>("ParentId"))
            .ToDictionary(
                a => a.Key,
                a => a.GroupBy(c => c.Field<string>("Id"))
                      .ToDictionary(
                          d => d.Key,
                          d => d.GroupBy(f => f.Field<string>("Key"))
                                .ToDictionary(
                                    g => g.Key,
                                    //you'll have to pick one of the value in the grouped values
                                    g => g.First().Field<string>("Value"))));

但是对象真的很复杂,我不明白为什么最后一个嵌套字典不是Dictionary<string, IList<string>>

我不想对这类代码进行维护......