I am looking for a way in LINQ to get a max Id record by using 'Group By' clause
Consider the following Sample data
Table: ProcessAud
ProcessSeq ProjectSeq ProjectValue Active
11 1 50000 Y
12 1 10000 Y
13 2 70000 Y
14 2 90000 Y
In which I want to get two records as a list such that is second and fourth
records (i.e) ProcessSeq 12 and 14. And I tried it like following
var ProcessAudList = ProcessAudService.FilterBy(x => x.Active == "Y"
).GroupBy(x => x.ProjectSeq).Max().ToList();
It is not working properly, So how to do it in LINQ. Please anybody help.
In SQL, it is very simple to do: SELECT * FROM [dbo]. [tblOrderDeliveryGroup] t1 WHERE [DeliveryGroupId] IN ( SELECT MAX([DeliveryGroupId]) FROM [dbo].
In LINQ, you can find the maximum element of the given sequence by using Max() function. This method provides the maximum element of the given set of values.
GroupBy & ToLookup return a collection that has a key and an inner collection based on a key field value. The execution of GroupBy is deferred whereas that of ToLookup is immediate. A LINQ query syntax can be end with the GroupBy or Select clause.
You want to pick top record from each group.
var ProcessAudList = ProcessAudService.Where(x => x.Active == "Y")
.GroupBy(x => x.ProjectSeq, (key,g)=>g.OrderByDescending(e=>e.ProjectValue).First());
Check demo code
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With