日期之间的Linq查询 [英] Linq query between dates
问题描述
if ((!(searchStartDate == default(DateTime))) && (!(searchEndDate == default(DateTime))))
{
requests = requests.Where(x => x.CreatedDate >= searchStartDate && x.CreatedDate <= searchEndDate);
}
当我尝试使用searchEndDate
搜索时,日期不包括在内
When I try to search with searchEndDate
the date isn't included
例如),当开始日期为14/4/15且结束日期为14/4/15时,不返回任何结果,但当开始日期为14/4/15且结束日期为15/4/15时返回14/4/15
Eg.) When the start date is 14/4/15 and end date is 14/4/15 no results are returned but when the start date is 14/4/15 and end date is 15/4/15 results are returned for the 14/4/15
推荐答案
我强烈怀疑问题是您的开始日期和结束日期值与时间点完全相同-因此,只有 at 值将会找到确切的时间点.
I strongly suspect the problem is that your start and end date values are the exact same point in time - so only values at that exact point in time will be found.
例如,假设您拥有:
searchStartDate: 2015-04-15T00:00:00
searchEndDate: 2015-04-15T00:00:00
Sample CreatedDate: 2015-04-15T12:34:56
然后CreatedDate
不在searchStartDate
和searchEndDate
之间.您真的认为它是:
Then the CreatedDate
doesn't fall between searchStartDate
and searchEndDate
. You're really thinking of it as:
// Look ma, no time of day!
searchStartDate: 2015-04-15
searchEndDate: 2015-04-15
但由于DateTime
是损坏的模型,则无法使用类型系统来表明这一点.相反,您基本上需要手工完成:
but because DateTime
is a broken model, you can't indicate that with the type system. Instead, you basically need to do it by hand:
if (searchStartDate != default(DateTime) && searchEndDate != default(DateTime))
{
// Include the *whole* of the day indicated by searchStartDate
DateTime inclusiveStart = searchStartDate.Date;
// Include the *whole* of the day indicated by searchEndDate
DateTime exclusiveEnd = searchEndDate.Date.AddDays(1);
requests = requests.Where(x => x.CreatedDate >= inclusiveStart
&& x.CreatedDate < exclusiveEnd);
}
您也可以在查询中使用.Date
,但是效率可能会较低,因为它实际上涉及对每个存储值的计算-而我的方法只对边界执行一次计算.
You could put use .Date
in the query as well, but that may well be less efficient, as it effectively involves a calculation on each stored value - whereas my approach instead performs a calculation on the bounds instead, just once.
这篇关于日期之间的Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!