views:

80

answers:

2

Hi,

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 statement, possible?

Thx,

+8  A: 
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);
Lee
Nice and correct but why reuse the 'c' name in the group part? I think `.Where(g => ..).Sum(g => ...)` is so much clearer.
Henk Holterman
+4  A: 

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();
Jon Skeet