【发布时间】:2012-02-02 15:22:04
【问题描述】:
我在从 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();
【问题讨论】:
-
@M.Babcock 在那个问题的后面有一个很好的答案:stackoverflow.com/a/6330485/444244
-
还有比这更好的...
-
看看the answer。
-
@Serge 我同意morelinq 是最好的,但我担心这个项目会阻碍添加新库。