LINQ: How to get the Max Id with a group by clause?
When you use GroupBy extension, method will return you IGrouping instance and you should query IGrouping instance like below;
var ProcessAudList = collection.Where(x => x.Active == "Y").GroupBy(x => x.ProjectSeq).Select(x => x.OrderByDescending(a => a.ProcessSeq).FirstOrDefault()).ToList();
Hope this helps
You're most of the way there, but Max
is the wrong term to use.
Each IGrouping
is an IEnumerable
(or IQueryable
) sequence of its own, so you can use OrderBy
and First
clauses to get the answer you need:
var ProcessAudList = ProcessAudService .FilterBy(x => x.Active == "Y") .GroupBy(x => x.ProjectSeq) .Select(grp => grp.OrderByDescending(x => x.ProcessSeq).First()) .ToList();
The Select
clause will process each of the groups, order the groups descending by ProcessSeq
and select the first one. For the data you provided this will select the rows with ProcessSeq
equal to 12 and 14.