C#DataTable组并加入New DataTable

问题描述 投票:0回答:1

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

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();
c# datatable group-by linq-to-sql
1个回答
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();
© www.soinside.com 2019 - 2024. All rights reserved.