如何在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()
它返回记录1
和4
.如何使用LINQ
获取具有最高ID
的ContactID
? (即返回3
和6
)
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()