[英]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 12I first of all need to Group By City & Sum Total so I have 我首先需要按城市和总计分组,所以我有
Sydney 23 London 21
Next I need to filter for those that entries where the total is > 20 接下来,我需要过滤那些总数大于20的条目
\nSydney 23 悉尼23\nLondon 21 伦敦21\n
And what I finally need is the total of these entries, eg 44 我最后需要的是这些条目的总数,例如44
I really want to do it in 1 single LINQ statement, possible? 我真的很想在1条LINQ语句中做到这一点,可能吗?
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: Lee的几种替代方法:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.