How to select last record in a LINQ GroupBy clause

后端 未结 5 888
长发绾君心
长发绾君心 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 03:54

    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.

    0 讨论(0)
  • 2020-12-11 03:57

    You can order you items

    Mains.GroupBy(l => l.ContactID)
    .Select(g=>g.OrderByDescending(c=>c.ID).FirstOrDefault()) 
    .ToList()
    
    0 讨论(0)
  • 2020-12-11 04:00

    Use OrderByDescending on the items in the group:

    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; a group will always have at least one item so you can use First() safely.

    0 讨论(0)
  • 2020-12-11 04:06

    You could use MoreLinq like this for a shorter solution:

    Main.OrderByDescending(i => i.Id).DistinctBy(l => l.ContactID).ToList();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题