user1889838
user1889838

Reputation: 343

Get Distinct List of object with latest value

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?

Upvotes: 5

Views: 2301

Answers (2)

PiotrWolkowski
PiotrWolkowski

Reputation: 8792

As an alternative you can use MoreLINQ and DistinctBy:

var res = products
    .DistinctBy(p => p.Name)
    .OrderBy(p => p.TimeStamp)
    .ToList();

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

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.

Upvotes: 13

Related Questions