Reputation: 39
I have a DataTable that looks like this:
Id Value
123 4.0
123 5.0
234 1.0
345 2.0
345 3.0
I want to end up with (probably a new DataTable) that contains the sum of values grouped by Id like this:
Id SumOfValue
123 9.0
234 1.0
345 5.0
Here is my code,
var query = from row in dTable.AsEnumerable()
group row by row.Field<double>("ITEM_NO") into grp
orderby grp.Key
select new
{
ITEM_NO = grp.Key,
sum = grp.Sum(r = r.Field<double>("ITEM_STOCK"))
};
I am getting an error that r is undefined
, also I am not able to add these values in a new datatable.
Does anyone know how to write this?
Thanks.
Upvotes: 1
Views: 279
Reputation: 16657
I believe you are not specifying the operation correctly. Try this:
var query = from row in dTable.AsEnumerable()
group row by row.Field<double>("ITEM_NO") into grp
orderby grp.Key
select new
{
ITEM_NO = grp.Key,
sum = grp.Sum(r => r.Field<double>("ITEM_STOCK"))
};
The difference is r => r.Field
instead of r = r.Field
.
Upvotes: 3