blisher
blisher

Reputation: 75

How to sort a DateTime elements

I have as following:

Class Video, which contains among others a DateTime property (when a Video is posted).

Now I want to display few of recent videos added, i have a List of videos, and I am looking for lambda expressions to compare two DateTime elements

This doesn`t work:

List<Video> list = new List<Video>();
//.. Adding some videos
List<Video> orderedList = list.OrderBy(x => x.DatePosted).ToList();

Thanks in advance for helping

Upvotes: 0

Views: 96

Answers (2)

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

You can use OrderByDescending to get the newest videos and Take to get only your few videos:

const int aFew = 5;
var fewRecentVideos = list.OrderByDescending(v => v.DatePosted).Take(aFew);

Upvotes: 3

Will Custode
Will Custode

Reputation: 4594

list.OrderBy(x => (DateTime.Now - x.DatePosted).TotalMinutes).ToList( );

You can convert the DateTime into a TimeSpan relative to today/now and do either ascending or descending order.

Upvotes: 1

Related Questions