C# 在 Linq to SQL 中对可为空的 DateTime 进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1107767/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:25:14  来源:igfitidea点击:

Ordering nullable DateTime in Linq to SQL

c#linq-to-sqldatetime

提问by dkarzon

I have started using Linq to SQL for a project im working on and i have run into a problem when ordering by a DateTime field but since the DateTime allows nulls the nulls are coming up as less than the actual dates in there.

我已经开始将 Linq to SQL 用于我正在处理的项目,并且在按 DateTime 字段排序时遇到了问题,但由于 DateTime 允许空值,空值出现的时间少于那里的实际日期。

So i pretty much want the ones with a date to be at the top (ordered either way) then all the ones with no date set.

所以我非常希望有日期的那些在顶部(以任何一种方式排序)然后是所有没有设置日期的。

jobList = from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          select ju.Job;
return jobList.OrderByDescending(j => j.EndDate);

采纳答案by Matt Hamilton

This is a bit of a hack, but it appears to work with Linq to SQL:

这是一个小技巧,但它似乎适用于 Linq to SQL:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created ?? DateTime.MaxValue descending;

So I'm substituting the maximum possible DateTime value when the actual "Create" value is null. That'll put all the null values at the top.

因此,当实际的“创建”值为空时,我将替换最大可能的 DateTime 值。这会将所有空值放在顶部。

Another approach is to order by whether the date field has a value. This works too:

另一种方法是按日期字段是否有值来排序。这也有效:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created.HasValue descending
          orderby ju.Created descending;