开发者

Applying a filter to subsequences of a sequence using Linq

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 =开发者_如何学JAVA collection.Select(i => i.Id).Distinct();
foreach(var id in ids)
{
  mostRecentItems.Add(collection.Where(i => i.Id == id).OrderByDescending().First);
}

return mostRecentItems;


Most simply:

var mostRecentById = from item in list
                     group item by item.Id into g
                     select g.OrderByDescending(x => x.Year).First();


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() );


or more simply still:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜