在Linq to SQL中排序可为空的DateTime

dka*_*zon 22 c# datetime linq-to-sql

我已经开始使用Linq to SQL来处理正在进行的项目,并且我在使用DateTime字段进行排序时遇到了问题,但由于DateTime允许空值,因此空值将小于其中的实际日期.

所以我非常希望那些日期最重要的(按任意方式排序),然后是所有没有日期设置的日期.

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

Mat*_*ton 51

这有点像黑客,但它似乎与Linq一起使用SQL:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created ?? DateTime.MaxValue descending;
Run Code Online (Sandbox Code Playgroud)

所以当实际的"Create"值为null时,我将替换最大可能的DateTime值.这将把所有空值放在顶部.

另一种方法是根据日期字段是否具有值来排序.这也有效:

return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created.HasValue descending
          orderby ju.Created descending;
Run Code Online (Sandbox Code Playgroud)

  • 我不能完全理解为什么,但我发现你的第二个解决方案非常漂亮 (4认同)