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

发布于 2024-09-04 11:27:32 字数 355 浏览 4 评论 0原文

我有一个这样的列表:

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

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

Sydney 23
London 21

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

我真的想在 1 个 LINQ 语句中完成它,可能吗?

谢谢,

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,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伤痕我心 2024-09-11 11:27:32
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);
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);
猫卆 2024-09-11 11:27:32

Lee 的几种替代方法:

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

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

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文