Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Distinct List of object with latest value

Tags:

c#

list

I have a list of product objects

List<Product> products = new 
List<Product>() 
{
        new Product{ Name= "A", Code =1, TimeStamp= DateTime.Parse("26/06/2014 8:01") },
        new Product{ Name= "B", Code =2, TimeStamp= DateTime.Parse("26/06/2014 8:02") },
        new Product{ Name= "A", Code =1, TimeStamp= DateTime.Parse("26/06/2014 8:04") },
        new Product{ Name= "C", Code =5, TimeStamp= DateTime.Parse("26/06/2014 8:07") }
};

I want to get a distinct list of products with the latest Time value, so the expected output is -

Distinct Products
Name Code TimeStamp
A     1     8:04
B     2     8:02
C     5     8:07

I tried .GroupBy() but not working, any idea?

like image 881
user1889838 Avatar asked Jun 22 '14 10:06

user1889838


1 Answers

Using GroupBy is the right approach - order your groups, and take the first item, like this:

var res = products
    .GroupBy(p => p.Name)
    .Select(g => g.OrderByDescending(p => p. TimeStamp).First())
    .ToList();

The idea is to order each group by the timestamp in descending order, and then grab the first item from the sorted sub-list.

like image 115
Sergey Kalinichenko Avatar answered Oct 03 '22 21:10

Sergey Kalinichenko