In C# problem grouping by value and then summing
I am trying to sum the cost for a series of items grouped by a person's or开发者_开发技巧ganization. I believe the summation is working correctly but I am not seeing my grouping. The objects stored in rollup just contain the value of the summation. I'd expect them to have the organization in addition to the sum of the cost for that organization. What have I missed in this expression?
var rollup = OrgPersonList.GroupBy(
person => person.Person.Org).Select(group =>
group.Sum(price => price.Items.Sum(item =>
item.Cost)));
Well you're only selecting the sum - if you want the key as well, you should select that. For example:
var rollup = OrgPersonList.GroupBy(x => x.Person.Org)
.Select(group => new { group.Key,
Sum =group.Sum(x => x.Items.Sum(item => item.Cost))});
Note that I've used x
rather than person
or price
as it seems the same item encapsulates both.
Or as a query expression:
var rollup = from x in OrgPersonList
group x by x.Person.Org into grouped
select new { grouped.Key,
Sum =grouped.Sum(x => x.Items.Sum(item =>item.Cost))});
(Whitespace somewhat tight for formatting...)
Alternatively again, the group...by could calculate the sum for each entry, so the result just needs to be the sum of the entries in the group:
var rollup = from x in OrgPersonList
group x.Items.Sum(item => item.Cost) by x.Person.Org into grouped
select new { grouped.Key, Sum = grouped.Sum() });
精彩评论