简体   繁体   中英

Filter out oldest item when items have the same name

public class Foo
{
     public string Name {get; set;}
     public int Year {get; set;}
}

Say i have a List of Foo items. It is possible that some Foo items have the same name. In that case i want to filter out all but the most recent Foo item with that name. ( A Foo item can not have the same name AND the same Year )

Is there way to do this with a single LINQ statement ?

You can use GroupBy :

var result = items.GroupBy(foo => foo.Name)
                  .Select(g => g.OrderByDescending(foo => foo.Year).First())
                  .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM