降序排序不适用于DateTime

时间:2014-01-30 14:33:03

标签: linq linq-to-sql

所以我有这个linq-to-sql查询:

DateTime dtePast = new DateTime(1970, 1, 1);

Datetime newestDate = (from e in tblExpenses
join rd in tblRepairDetails on e.ExpenseItemID equals rd.ExpenseItemID
orderby (DateTime)e.ExpenseDate descending
select e.ExpenseDate).DefaultIfEmpty(dtePast).First();

如果没有.First()方法,它会返回这4个日期的完整列表:

3/18/2013 12:00 AM

5/14/2012 12:00 AM

2/07/2012 12:00 AM

1/10/2012 12:00 AM

然而,使用.First()方法,它将返回1/10/2012而不是3/18/2013。无论我尝试什么,都会返回最旧的日期而不是最新的日期。我如何获得最新的约会?我已经花了三个小时在这上面,无法弄明白。

==编辑#1 ==

以下是实际代码:

DateTime dteNewestOccurrance = (from ve in context.tblVehicleExpenses
join rd in context.tblVehicleRepairDetails on ve.ExpenseItemID equals rd.ExpenseItemID
where ve.VehicleID == strVehicleID && rd.ActivityName == a.ActivityID
orderby (DateTime)ve.ExpenseDate descending
select ve.ExpenseDate).DefaultIfEmpty(dtePast).First();

同样,此代码拒绝返回最新日期(2013年3月18日)。我尝试过升序,降序,.OrderByDescending()等等,并拒绝提供最新的日期。

==编辑#2 ==

好吧,经过一些测试,这段代码可以工作:

var varOccurranceList = from ve in context.tblVehicleExpenses
  join rd in context.tblVehicleRepairDetails on ve.ExpenseItemID equals rd.ExpenseItemID
  where ve.VehicleID == strVehicleID && rd.ActivityName == a.ActivityID
  orderby (DateTime)ve.ExpenseDate descending
  select ve.ExpenseDate;

DateTime dteNewestOccurrance = DateTime.Now;
if (varOccurranceList.Count() > 0)
   dteNewestOccurrance = varOccurranceList.First();
else
   dteNewestOccurrance = dtePast;

似乎.DefaultIfEmpty()和/或.First()会破坏代码并导致意外结果。我想要么我不明白如何正确使用这两个Linq方法,或者它们有一些可怕的错误。我对此并不满意。

1 个答案:

答案 0 :(得分:1)

假设ExpenseDate可以为空,请尝试:

DateTime dteNewestOccurrance = (from ve in context.tblVehicleExpenses
join rd in context.tblVehicleRepairDetails on ve.ExpenseItemID equals rd.ExpenseItemID
where ve.VehicleID == strVehicleID && rd.ActivityName == a.ActivityID
orderby ve.ExpenseDate descending
select ve.ExpenseDate).FirstOrDefault() ?? dtePast;