如何在LINQ GroupBy子句中选择最后一条记录

问题描述:

我有下面的简单表,其中包含 ID ContactId Comment .

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

我要选择记录和GroupBy contactId.我使用了以下LINQ扩展方法语句:

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

它返回记录14.如何使用LINQ获取具有最高IDContactID? (即返回36)

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)

您可以订购商品

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