Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Model.OrderBy Date has no effect

I'm having some difficulties to sort my results by Date. Is there any special method? Because I'm doing this right now:

var db = new DB();
var articles = db.Articles;
var orderedArticles = articles.OrderBy(a => a.Date);
return View(orderedArticles.ToList());

Where Date is a datetime field. And there is no effect for OrderBy(..) or OrderByDescending(..)

So I managed to check what is happening.

Everytime I add a new Article I'm just using the date on not the time so if I have two articles both for the same day for example: with:

var orderedArticles = db.Articles.OrderByDescending(a => a.Date).ToList();

I would have

Id         Title                           Date
10         First Added  Article            16/09/2009 00:00
11         Second Added Article            16/09/2009 00:00
15         Old Article Added Later         15/09/2009 00:00

So you can see that is filtering by date, but the thing is when I have the same date the sorting loses the focus. So what I did is, orderBy two different contexts like first order by Id and later order by Date:

var orderedArticles = db.Articles.OrderByDescending(a => a.Id).OrderByDescending(a => a.Date).ToList();

So after this I have the following:

Id         Title                           Date
11         Second Added Article            16/09/2009 00:00
10         First Added  Article            16/09/2009 00:00
15         Old Article Added Later         15/09/2009 00:00

I really don't know if this is the right way to do it because the main problem is that when you submit a date field like 16/09/2009 it sets the time to 00:00 and this is a problem on this situation.

like image 726
zanona Avatar asked Sep 16 '09 13:09

zanona


2 Answers

Looking at the answer you provided (which FYI should be moved into the question as an edit), you should apply a ThenBy, rather than a new OrderBy:

var articles = db.Articles.OrderByDescending(a => a.Date).ThenBy(a => a.Id).ToList();
like image 163
Dan Atkinson Avatar answered Oct 17 '22 11:10

Dan Atkinson


This code looks good. You should check what is really in the Date field and make sure you do not for example only set the Date of the DateTime object on the database level, that would result in all DateTime objects of a certain date to point to 00:00:00 thus the LINQ would not know how to sort them.

like image 24
Robban Avatar answered Oct 17 '22 11:10

Robban