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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With