簡體   English   中英

LINQ 使用 Max() 到 select 單行

[英]LINQ Using Max() to select a single row

我在從 NHibernate 返回的 IQueryable 上使用 LINQ,我需要 select 在幾個字段中具有最大值的行。

我已經簡化了我堅持的部分。 我需要 select 我表中的一行,其中一個字段中有最大值。

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> ,這將很有幫助。

你也可以這樣做:

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

您可以按狀態分組並從最大的組中選擇一行:

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

第一個First()獲取第一組(狀態最大的行集); 第二個First()獲取該組中的第一行。
如果狀態始終為 unqiue,則可以將第二個First()替換為Single()

解決第一個問題,如果您需要將按某些條件分組的幾行與具有最大值的另一列一起使用,您可以執行以下操作:

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;

這個想法怎么樣:比

  1. 最大 Select
  2. Select 按最大值

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

再舉一個例子:

跟隨:

 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)

只需在一行中:

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

請注意,有兩個動作。 內部動作用於尋找最大值,外部動作用於獲取所需的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM