简体   繁体   English

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

[英]How to select last record in a LINQ GroupBy clause

I have the following simple table with ID , ContactId and Comment . 我有以下带IDContactIdComment的简单表。

在此输入图像描述

I want to select records and GroupBy contactId . 我想选择记录和GroupBy contactId I used this LINQ extension method statement: 我使用了这个LINQ扩展方法语句:

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

It returns record 1 and 4 . 它返回记录14 How can I use LINQ to get the ContactID with the highest ID ? 如何使用LINQ获取具有最高IDContactID (ie return 3 and 6 ) (即返回36

You can order you items 你可以订购物品

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

Use OrderByDescending on the items in the group: 对组中的项使用OrderByDescending

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

Also, there is no need for FirstOrDefault when selecting an item from the group; 此外,从组中选择项目时不需要FirstOrDefault ; a group will always have at least one item so you can use First() safely. 一个组将始终至少有一个项目,以便您可以安全地使用First()

Perhaps selecting with Max instead of OrderByDescending could result into improving of performance (I'm not sure how it's made inside so it needs to be tested): 也许选择使用Max而不是OrderByDescending可以提高性能(我不确定它是如何制作的,所以需要进行测试):

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

As I assume it could result into a query that will take MAX and then do SELECT * FROM ... WHERE id IN ({max ids here}) which could be significantly faster than OrderByDescending . 我认为它可能导致一个查询将采用MAX ,然后执行SELECT * FROM ... WHERE id IN ({max ids here}) ,这可能比OrderByDescending

Feel free to correct me if I'm not right. 如果我不对,请随意纠正我。

OrderByDescending OrderByDescending

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

is your best solution 是你最好的解决方案

It orders by the highest ID descending, which is pretty obvious from the name. 它以最高ID递减顺序排序,这从名称中非常明显。

您可以像这样使用MoreLinq来获得更短的解决方案:

Main.OrderByDescending(i => i.Id).DistinctBy(l => l.ContactID).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM