gpt4 book ai didi

c# - LINQ 使用 Max() 选择单行

转载 作者:IT王子 更新时间:2023-10-29 03:37:26 25 4
gpt4 key购买 nike

我在从 NHibernate 返回的 IQueryable 上使用 LINQ,我需要在几个字段中选择具有最大值的行。

我已经简化了我坚持的部分。我需要从我的表中选择一个字段中具有最大值的一行。

var table = new Table { new Row(id: 1, status: 10), new Row(id: 2, status: 20) }

from u in table
group u by 1 into g
where u.Status == g.Max(u => u.Status)
select u

这是不正确的,但我无法算出正确的形式。

顺便说一句,我实际上想要实现的大致是这样的:

var clientAddress = this.repository.GetAll()
.GroupBy(a => a)
.SelectMany(
g =>
g.Where(
a =>
a.Reference == clientReference &&
a.Status == ClientStatus.Live &&
a.AddressReference == g.Max(x => x.AddressReference) &&
a.StartDate == g.Max(x => x.StartDate)))
.SingleOrDefault();

我从上面的 lambda 开始,但我一直在使用 LINQPad 来尝试计算出选择 Max() 的语法。

更新

删除 GroupBy 是关键。

var all = this.repository.GetAll();

var address = all
.Where(
a =>
a.Reference == clientReference &&
a.Status == ClientStatus.Live &&
a.StartDate == all.Max(x => x.StartDate) &&
a.AddressReference == all.Max(x => x.AddressReference))
.SingleOrDefault();

最佳答案

我不明白你为什么要在这里分组。

试试这个:

var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);

迭代 table 的替代方法只有一次是这样的:

var result = table.OrderByDescending(x => x.Status).First();

如果 table 这很有用是一个 IEnumerable<T>不存在于内存中或即时计算的。

关于c# - LINQ 使用 Max() 选择单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9114863/

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