开发者

Linq/C#: Selecting and summing items from the result of a group by?

I have a list like this:

City   Total
Sydney 11
Dublin 9
London 12
Dublin 3
London 9
Sydney 12
I first of all need to Group By City & Sum Total so I have

Sydney 23
Dublin 12
London 21

Next I need to filter for those that entries where the total is > 20

Sydney 23
London 21

And what I finally need is the total of these entries, e.g. 44

I really want to do it in 1 single LINQ statem开发者_如何学运维ent, possible?

Thx,


int cityTotals = cities
    .GroupBy(c => c.City)
    .Select(grp => new { City = grp.Key, Total = grp.Sum(c => c.Total) })
    .Where(c => c.Total > 20)
    .Sum(c => c.Total);


A couple of alternative approaches to Lee's:

int cityTotals = cities
    .GroupBy(c => c.City)
    .Select(grp => grp.Sum(c => c.Total))
    .Where(total => total > 20)
    .Sum();

or

int cityTotals = cities
    .GroupBy(c => c.City, (key, grp) => grp.Sum(x => x.Total))
    .Where(total => total > 20)
    .Sum();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜