使用Linq和Group by将数据表转换为对象

max*_*sam 4 c# linq

我尝试将datatable转换为特殊格式的JSON

DataTable中的数据如下

col1 col2 col3 col4
---------------------
 A    B    c    D1
 A    B    c    D2
 A    B    c    D3
Run Code Online (Sandbox Code Playgroud)

尝试将其转换为对象数组

class obj {
 var col1;
 var col2;
 var col3;
 list<string> col4;
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用linq,但有点卡住了.

 var result = from row in dt.AsEnumerable()
                         group row by new
                         {
                             c1 = row["col1"],
                             c2 = row["col2"],
                             c3 = row["col3"]
                         }
                             into section
                             select new
                                 {
                                     item = section.Key

                                 };
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

var result = from row in dt.AsEnumerable()
             group row by new
             {
                 c1 = r.Field<string>("col1"),
                 c2 = r.Field<string>("col2"),
                 c3 = r.Field<string>("col3")
             } into section
             select new
             {
                 col1 = section.Key.c1,
                 col2 = section.Key.c2,
                 col3 = section.Key.c2,
                 col4 = section.Select(r => r.Field<string>("col4")).ToList()
             };
Run Code Online (Sandbox Code Playgroud)

  • `col4 = section.Select(r => r.Field <String>("col4")).ToList()`会更好. (2认同)