How to select last record in a LINQ GroupBy clause

后端 未结 5 927
长发绾君心
长发绾君心 2020-12-11 03:06

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

I want to select records and GroupBy contactId. I

5条回答
  •  甜味超标
    2020-12-11 04:11

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

    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.

    Feel free to correct me if I'm not right.

提交回复
热议问题