LINQ Using Max() to select a single row

前端 未结 6 1438
轻奢々
轻奢々 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: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 that is not present in memory or that is calculated on the fly.

提交回复
热议问题