0

If I have a List<MyType> as so, with each line representing an item in the collection:

{{ Id = 1, Year = 2010 },
{ Id = 1, Year = 2009 },
{ Id = 1, Year = 2008 },
{ Id = 2, Year = 2010 },
{ Id = 2, Year = 2009 },
{ Id = 2, Year = 2008 }}

I wish to retrieve a collection from this collection of the most recent item for each Id. What will the Linq for this look like?

Desired output:

{{ Id = 1, Year = 2010 },
{ Id = 2, Year = 2010 }}

I have a naiive implementation using a second list variable and a foreach loop, but it's inefficient.

//naiive implementation "p-code"
//...
var mostRecentItems = new List<MyType>();    
var ids = collection.Select(i => i.Id).Distinct();
foreach(var id in ids)
{
  mostRecentItems.Add(collection.Where(i => i.Id == id).OrderByDescending().First);
}

return mostRecentItems;

3 Answers 3

4

Most simply:

var mostRecentById = from item in list
                     group item by item.Id into g
                     select g.OrderByDescending(x => x.Year).First();
4
  • Thanks. TBH, I haven't got my head quite around GroupBy. If anyone knows of a simple explanation online please post.
    – Ben Aston
    Nov 24, 2010 at 19:18
  • @Ben: This groups together everything with the same ID, then sorts each group by year, then takes the first value - i.e. the one with the highest year.
    – Jon Skeet
    Nov 24, 2010 at 19:30
  • @Jon - is the "group" conceptually analogous to a temporary table? Clarification: does the grouping result in a sequence of subsequences matching the "by" upon which a subquery can be executed?
    – Ben Aston
    Nov 24, 2010 at 19:40
  • @Ben: Yes - each group has a Key property (the Id in this case) but is also a subsequence.
    – Jon Skeet
    Nov 24, 2010 at 20:31
1

Group by id, then select the first item in each group ordered in a descending fashion.

 var mostRecentItems = collection.GroupBy( c => c.Id )
                                 .Select( g => g.OrderByDescending( i => i.Year ).First() );
0

or more simply still:

var result = list
                .GroupBy(i => i.Id)
                .Select(g => new {Id = g.Key, Year = g.Max(y => y.Year)});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.