我已经开始使用Linq to SQL进行正在进行的项目,并且在按DateTime字段进行排序时遇到了问题,但是由于DateTime允许使用null,因此null少于那里的实际日期。

因此,我非常希望带有日期的控件位于顶部(以任何一种方式排序),然后是所有未设置日期的控件。

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

最佳答案

这有点hack,但是它似乎可以与Linq to SQL一起使用:

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

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

另一种方法是根据日期字段是否具有值进行排序。这也适用:
return from ju in context.Job_Users_Assigned
          where ju.UserID == user.ID
          orderby ju.Created.HasValue descending
          orderby ju.Created descending;

关于c# - 在Linq中向SQL订购可空的DateTime,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1107767/

10-10 10:05