How to select the last entry in a LINQ GroupBy clause

I have the following simple table with id, ContactId and Comment.

enter image description here

I want to select records and GroupBy contactId . I used this LINQ extension statement:

 Mains.GroupBy(l => l.ContactID) .Select(g => g.FirstOrDefault()) .ToList() 

It returns record 1 and 4 . How can I use LINQ to get the ContactID with the highest ID ? (i.e. return 3 and 6 )

+5
source share
4 answers

You can order items

 Mains.GroupBy(l => l.ContactID) .Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault()) .ToList() 
+12
source

Use OrderByDescending for items in a group:

 Mains.GroupBy(l => l.ContactID) .Select(g => g.OrderByDescending(l => l.ID).First()) .ToList(); 

In addition, there is no need for FirstOrDefault when selecting an item from a group; a group will always have at least one element so that you can use First() safely.

+5
source

Perhaps choosing Max instead of OrderByDescending can lead to better performance (I'm not sure how this is done internally, so I need to test it):

 var grouped = Mains.GroupBy(l => l.ContactID); var ids = grouped.Select(g => g.Max(x => x.Id)); var result = grouped.Where(g => ids.Contains(g.Id)); 

I suppose this can lead to a query that takes Max , and then do SELECT * FROM ... WHERE id IN ({max ids here}) , which can be significantly faster than OrderByDescending .

Feel free to correct me if I'm wrong.

+3
source

OrderByDescending

 Mains.GroupBy(l => l.ContactID) .Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault()) .ToList() 

- your best decision

He orders the highest identifier in descending order, which is pretty obvious from the name.

+1
source

All Articles