Group members and select a specific member from each group using LINQ

To do this, there must be one liner, and I just can not find it.

Given this request:

from x in new XPQuery<XPContent>(s)
select new { x.Category, x.ContentType, x.Name, x.ContentID, x.Date }

I need to select the record with the highest date for each individual ContentID. Can this be done using LINQ? Now I am doing this:

var q = (from x in new XPQuery<XPContent>(s)
            select new { x.Category, x.ContentType, x.Name, x.ContentID, x.Date }).ToList();

var r = q.ToLookup(item => item.ContentID);
foreach (var rItem in r) {
    var s = rItem.OrderByDescending(a => a.Date).First();
    /* do stuff with s */
}

... but ToLookup feels awkward. Or do I have the best (easiest) solution?

In addition, I know that I should not use ToList, but please just ignore it for now.

Thanks in advance!

+5
source share
1 answer

I think you want:

var q = from x in new XPQuery<XPContent>(s)
        group x by x.ContentID into g
        let latest = g.OrderByDescending(a => a.Date).First()
        select new 
        {
            latest.Category, latest.ContentType,
            latest.Name, latest.ContentID, latest.Date
        };

( , "" , , , MaxBy.)

; ContentId, , .

+6

All Articles