LINQ Using Max() to select a single row

我正在对从 NHibernate 返回的 IQueryable 使用 LINQ,并且需要在两个字段中选择具有最大值的行。

I've simplified the bit that I'm sticking on. I need to select the one row from my table with the maximum value in one field.

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

This is incorrect but I can't work out the right form.

顺便说一下,我实际上想要达到的是大约这样:

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 ()的语法。

UPDATE

删除 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();
340955 次浏览

您可以根据状态进行分组,并从最大的组中选择一行:

table.GroupBy(r => r.Status).OrderByDescending(g => g.Key).First().First();

第一个 First()获取第一组(具有最大状态的行集) ; 第二个 First()获取该组中的第一行。
如果状态始终为 unqiue,则可以将第二个 First()替换为 Single()

我不明白你们为什么要在这里集合。

试试这个:

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>或者是动态计算的 IEnumerable<T>,那么这是有帮助的。

你也可以这样做:

(from u in table
orderby u.Status descending
select u).Take(1);

为了解决第一个问题,如果需要根据某些条件将几行分组,然后将另一列的 max 值分组,那么可以这样做:

var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;

简单地用一行字 表示:

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

注意有两个动作。 内部动作是为了找到最大值, 外部动作是为了得到所需的对象。

还有一个例子:

跟随:

 qryAux = (from q in qryAux where
q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
== q.FieldPk select pp.OrdSeq).Max() select q);

平等:

 select t.*   from nametable t  where t.OrdSeq =
(select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

这个想法怎么样: 总比

  1. Select max
  2. 按最大值选择

var maxRow = table.Aggregate(
(a, b) => a.Status > b.Status ? a : b  // whatever you need to compare
);