Linq - Grouping with sum calculation

前端 未结 2 431
生来不讨喜
生来不讨喜 2021-01-23 02:04

Linq noob here. How do I correct this?

                var result = (from row in rulestable.AsEnumerable()
                         let sup = row.Field

        
2条回答
  •  悲哀的现实
    2021-01-23 02:17

    Inside the lambda, grp (which I've renamed r for row to distinguish from the group itself) is going to be a DataRow. The compiler doesn't know what datatype grp[string] returns, since it just returns an object. Try this:

    DataTable rulestable = new DataTable();
    rulestable.Columns.Add("Supplier");
    rulestable.Columns.Add("Amount", typeof(decimal));
    rulestable.Columns.Add("Advance", typeof(decimal));
    rulestable.Columns.Add("Balance", typeof(decimal));
    rulestable.Columns.Add("VatRate", typeof(decimal));
    rulestable.Rows.Add("S1", 10M, 5M, 5M, 1M);
    rulestable.Rows.Add("S1", 10M, 5M,  5M, 1M);
    
    var result = (from row in rulestable.AsEnumerable()
                  let sup = row.Field("Supplier")
                  let amo = row.Field("Amount")
                  let adv = row.Field("Advance")
                  let bal = row.Field("Balance")
                  let vat = row.Field("VatRate")
                  group row by new { sup, vat } into grp
                  select new
                  {
                      Supplier = grp.Key.sup,
                      Amount   = grp.Sum(r => r.Field("Amount")),
                      Advance  = grp.Sum(r => r.Field("Advance")),
                      Balance  = grp.Sum(r => r.Field("Balance")),
                      VatRate  = grp.Key.vat
                  }).ToList();
    
    Input:
    Supplier | Amount | Advance | Balance | VatRate
    -----------------------------------------------
       S1    |   10   |    5    |    5    |    1
    -----------------------------------------------  
       S1    |   10   |    5    |    5    |    1
    
    Result:
    Supplier | Amount | Advance | Balance | VatRate
    -----------------------------------------------
       S1    |   20   |    10   |    10   |    1
    

    Using the input you supplied, this gives the results you expected above.

提交回复
热议问题