Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: How to get the Max Id with a group by clause?

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.

like image 514
Md Aslam Avatar asked Feb 03 '16 06:02

Md Aslam


People also ask

How do you select records with Max ID that GroupBy multiple columns in LINQ to SQL?

In SQL, it is very simple to do: SELECT * FROM [dbo]. [tblOrderDeliveryGroup] t1 WHERE [DeliveryGroupId] IN ( SELECT MAX([DeliveryGroupId]) FROM [dbo].

How do you find the maximum value in LINQ?

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.

What does LINQ GroupBy return?

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.


2 Answers

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

like image 94
Hari Prasad Avatar answered Sep 27 '22 17:09

Hari Prasad


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

like image 22
Cihan Uygun Avatar answered Sep 27 '22 19:09

Cihan Uygun