I have the following simple table with ID, ContactId and Comment.
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
)
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.
LINQ query syntax always ends with a Select or Group clause.
You can order you items
Mains.GroupBy(l => l.ContactID)
.Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault())
.ToList()
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