C#DataTable组并加到New DataTable中

时间:2019-02-28 04:33:08

标签: c# datatable group-by linq-to-sql

我有一个这样的数据表:

id   itemcode   uom   rate      qty   smallest_qty  location

001  Item001    KG    1000.00   1     1000          1001
002  Item001    G     1.00      200   200           1001
003  Item002    Pcs   1.00      10    10            1001
004  Item002    PKT   30.00     2     60            1001

我想将新表分组为如下表:

itemcode    location   smallest_qty

Item001     1001       1200
Item002     1001       70

但是我尝试编译以下内容以生成目标表,但是失败了。

DataTable dt_1 = dt.AsEnumerable()
     .GroupBy(r => r.Field<String>("itemcode"),
              r => r.Field<String>("location"))
     .Select (g =>
              {
                  var row = dt.NewRow();

                  row["itemcode"] = g.Key.itemcode;
                  row["location"] = g.Key.location;
                  row["smallest_qty"] = g.Sum(r => r.Field<Decimal>("smallest_qty"));

                  return row;
               }).CopyToDataTable();

1 个答案:

答案 0 :(得分:0)

DataTable dt_1 = dt.AsEnumerable()
     .Select(a => new {   
                  itemcode = a.Field<String>("itemcode"),
                  location = a.Field<String>("location"),
                  smallest_qty = a.Field<Decimal>("smallest_qty")                                                    
                       })
     .GroupBy(r => new{r.itemcode,r.location})
     .Select(g =>{
                   var row = dt.NewRow();
                   row["itemcode"] = g.Key.itemcode;
                   row["location"] = g.Key.location;
                   row["smallest_qty"] = g.Sum(r => r.smallest_qty);
                   return row;
     }).CopyToDataTable();