使用Linq到GroupBy和Sum数据表

Leo*_*ton 6 c# linq datatable group-by sum

嗨,我有一个像这样的数据表:

Id             Amount 1        Amount 2        Amount 3  
1              2               2               2  
12             4               6               4  
12             6               6               5  
22             7               2               1  
22             7               2               2

我需要得到这样的数据表:

Id             Amount 1        Amount 2        Amount 3  
1              2               2               2  
12             10              12              9    
22             14              4               3

我最初尝试在匿名方法中执行此操作,但我需要将其返回到另一个无法使用匿名方法完成的类.我的第二次尝试是这样做,以便它可以返回:

DataTable ddt = dt.AsEnumerable()
        .Sum(g => g.Field<int>("Amount 1"))
        .GroupBy(g => new { Col1 = g["ID"] })
        .Select(g => g.OrderBy(r => r["ID"]).First())
        .CopyToDataTable();
Run Code Online (Sandbox Code Playgroud)

这段代码肯定不会编译但是如果可能的话,任何帮助/建议都会非常感激.我对linq很新.

Art*_*aca 21

您可以GroupBy先将组投影到DataRows,然后创建DataTable使用CopyToDataTable扩展名:

var newDt = dt.AsEnumerable()
              .GroupBy(r => r.Field<int>("Id"))
              .Select(g =>
              {
                  var row = dt.NewRow();

                  row["Id"] = g.Key;
                  row["Amount 1"] = g.Sum(r => r.Field<int>("Amount 1"));
                  row["Amount 2"] = g.Sum(r => r.Field<int>("Amount 2"));
                  row["Amount 3"] = g.Sum(r => r.Field<int>("Amount 3"));

                  return row;
              }).CopyToDataTable();
Run Code Online (Sandbox Code Playgroud)