Using Linq to GroupBy and Sum datatable

前端 未结 3 1526
感动是毒
感动是毒 2021-01-02 14:02

Hi, I have a Datatable like this:

Id             Amount 1        Amount 2        Amount 3  
1              2               2               2  
12         


        
3条回答
  •  孤独总比滥情好
    2021-01-02 14:36

    You can GroupBy first, then project the groups to DataRows, then create the DataTable using CopyToDataTable extension:

    var newDt = dt.AsEnumerable()
                  .GroupBy(r => r.Field("Id"))
                  .Select(g =>
                  {
                      var row = dt.NewRow();
    
                      row["Id"] = g.Key;
                      row["Amount 1"] = g.Sum(r => r.Field("Amount 1"));
                      row["Amount 2"] = g.Sum(r => r.Field("Amount 2"));
                      row["Amount 3"] = g.Sum(r => r.Field("Amount 3"));
    
                      return row;
                  }).CopyToDataTable();
    

提交回复
热议问题