Get a separate list of objects with the last value

I have a list of objects product

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 great list of products with the most recent time value, so the expected result is

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

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

+4
source share
2 answers

Usage GroupByis the right approach - order your groups and take the first element, for example:

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

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

+8
source

Alternatively, you can use MoreLINQ and DistinctBy:

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

Source: https://habr.com/ru/post/1545538/


All Articles