asp.net-mvc ASP.NET MVC - Model.OrderBy Date 无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1433088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC - Model.OrderBy Date has no effect
提问by zanona
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(..)
其中 Date 是日期时间字段。并且对OrderBy(..)或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:
所以你可以看到它是按日期过滤的,但问题是当我有相同的日期时,排序失去了焦点。所以我所做的是, orderBy 两个不同的上下文,例如首先按 Id 订购,然后按日期订购:
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.
我真的不知道这是否是正确的方法,因为主要问题是当您提交像 16/09/2009 这样的日期字段时,它会将时间设置为 00:00,这在这种情况下是一个问题。
采纳答案by Robban
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.
这段代码看起来不错。您应该检查 Date 字段中的实际内容,并确保您不例如仅在数据库级别设置 DateTime 对象的日期,这会导致某个日期的所有 DateTime 对象指向 00:00:00因此 LINQ 不知道如何对它们进行排序。
回答by Dan Atkinson
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:
查看您提供的答案(仅供参考,应将其作为编辑移入问题中),您应该应用 ThenBy,而不是新的 OrderBy:
var articles = db.Articles.OrderByDescending(a => a.Date).ThenBy(a => a.Id).ToList();

