Linq/C#:从一组结果中选择和求和项目?

And*_*ite 1 c# linq select group-by where-clause

我有一个这样的列表:

City   Total
Sydney 11
Dublin 9
London 12
Dublin 3
London 9
Sydney 12
我首先需要Group By City和Sum Total所以我有

Sydney 23
Dublin 12
London 21

接下来我需要过滤那些总数> 20的条目

Sydney 23
London 21

我最终需要的是这些条目的总数,例如44

我真的想在一个单一的LINQ语句中做到这一点,可能吗?

谢谢,

Lee*_*Lee 9

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);
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 6

Lee的几种替代方法:

int cityTotals = cities
    .GroupBy(c => c.City)
    .Select(grp => grp.Sum(c => c.Total))
    .Where(total => total > 20)
    .Sum();
Run Code Online (Sandbox Code Playgroud)

要么

int cityTotals = cities
    .GroupBy(c => c.City, (key, grp) => grp.Sum(x => x.Total))
    .Where(total => total > 20)
    .Sum();
Run Code Online (Sandbox Code Playgroud)