Linq noob here. How do I correct this?
var result = (from row in rulestable.AsEnumerable()
let sup = row.Field
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.