LINQ order a collection of objects by date in descending order

c# entity-framework linq

Question

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); 
1
4
4/19/2013 12:35:25 PM

Accepted Answer

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.

5
10/17/2016 10:18:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow