gpt4 book ai didi

c# - 是否有 LINQ 查询会给我几个最大值的总和?

转载 作者:行者123 更新时间:2023-11-30 19:21:13 24 4
gpt4 key购买 nike

我有几个位置的交易数据表,我需要从位置的子集中找到每个位置的最大值之和。想象一下下表:

location  year  transactions
123 2009 57
124 2009 23
125 2009 45
123 2010 64
124 2010 12
125 2010 66

因此,如果我只查找位置 123 和 124 的数据,代码应该为 2010 年的位置 123 选择值 64,为 2009 年的位置 124 选择值 23。

我有以下代码,它可以找到每个位置的最大值,然后将其添加到运行总计中。

int total = 0;

foreach (var location in locationIds)
{
int? temp = transactions.Where(t => t.Location == location)
.Max(t => t.Transactions);
if (temp.HasValue)
{
total += temp.Value;
}
}

有没有更优雅的编码方式?

最佳答案

我使用的是您在上面示例中的表格中使用的命名。从您的代码来看,您可能需要相应地更改一些名称......但我不能肯定:

var locationsToInclude = new List<int> { 123, 124 };

var sum = transaction
.Where(t => locationsToInclude.Contains(t.location))
.GroupBy(t => t.location)
.Sum(g => g.Max(t => t.transactions));

关于c# - 是否有 LINQ 查询会给我几个最大值的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3865026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com