Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ order a collection of objects by date in descending order

I have a bunch of objects(products) and I want to order them by date created in descending order first and then only display the top 10 records. The format of the date created(DateTime) is as as follow.

4/4/2007 12:00:00 AM

This is what I have tried.

How can I sort the top 10 in descending order by date?

var productLatestReleases = (from p in visualsProduct
                                 from pf in p.DomainObjectFields
                                 select p).Distinct().OrderByDescending(d => d.DateCreated).Take(10); 
like image 451
Arianule Avatar asked Apr 19 '13 12:04

Arianule


1 Answers

Since you are describing the format of the date, I suppose that the datatype of the DateCreated property is string. If it is then you could do:

.OrderByDescending(d => Convert.ToDateTime(d.DateCreated)).Take(10)

Also, your Distinct() will not have much effect if you don't specify your own equality to compare.

like image 163
Andreas Johansson Avatar answered Oct 05 '22 09:10

Andreas Johansson