Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select last record in a LINQ GroupBy clause

Tags:

c#

linq

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 method 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)

like image 240
RaelB Avatar asked Jul 11 '16 10:07

RaelB


People also ask

Why does Select comes in last in LINQ?

The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.

Which of the following clauses can be used to end a LINQ query expression?

LINQ query syntax always ends with a Select or Group clause.


1 Answers

You can order you items

Mains.GroupBy(l => l.ContactID)
.Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault()) 
.ToList()
like image 109
tym32167 Avatar answered Sep 30 '22 08:09

tym32167