Perhaps choosing Max instead of OrderByDescending can lead to better performance (I'm not sure how this is done internally, so I need to test it):
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));
I suppose this can lead to a query that takes Max , and then do SELECT * FROM ... WHERE id IN ({max ids here}) , which can be significantly faster than OrderByDescending .
Feel free to correct me if I'm wrong.
source share