Convert Datatable to Object with Linq and Group by

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I try to convert datatable into JSON with special format

Data in DataTable is as follow

col1 col2 col3 col4 ---------------------  A    B    c    D1  A    B    c    D2  A    B    c    D3 

Try to convert it to a object array like

class obj {  var col1;  var col2;  var col3;  list<string> col4; } 

I try to use linq, but kinda get stuck.

 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                                   }; 

回答1:

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()              }; 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!