LINQ Using Max() to select a single row

前端 未结 6 1415
轻奢々
轻奢々 2020-12-02 16:13

I\'m using LINQ on an IQueryable returned from NHibernate and I need to select the row with the maximum value(s) in a couple of fields.

I\'ve simplified the bit tha

相关标签:
6条回答
  • 2020-12-02 16:46

    Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:

    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;
    
    0 讨论(0)
  • 2020-12-02 16:48

    Simply in one line:

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

    Notice that there are two action. the inner action is for finding the max value, the outer action is for get the desired object.

    0 讨论(0)
  • 2020-12-02 16:49

    I don't see why you are grouping here.

    Try this:

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

    An alternate approach that would iterate table only once would be this:

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

    This is helpful if table is an IEnumerable<T> that is not present in memory or that is calculated on the fly.

    0 讨论(0)
  • 2020-12-02 16:57

    You can group by status and select a row from the largest group:

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

    The first First() gets the first group (the set of rows with the largest status); the second First() gets the first row in that group.
    If the status is always unqiue, you can replace the second First() with Single().

    0 讨论(0)
  • 2020-12-02 17:01

    You can also do:

    (from u in table
    orderby u.Status descending
    select u).Take(1);
    
    0 讨论(0)
  • 2020-12-02 17:06

    More one example:

    Follow:

     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);
    

    Equals:

     select t.*   from nametable t  where t.OrdSeq =
            (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)
    
    0 讨论(0)
提交回复
热议问题