[英]how does one compare the date part of a nullable datetime in a linq / lambda query?
I have something like the following: 我有以下内容:
new ObservableCollection<SomeData>(SomeDataCollection.Where(a => a.AGD_Category.Equals((int)AGD_CategoryEnum.Med) && ((a.AGG_DateStart.Date <= SelectedUntill) && (a.AGG_DateEnd.Value.Date >= SelectedFrom))));
now my a.AGG_DateEnd is a nullable datetime and whenever there is a null value in the list I get an exception because of the "a.AGG_DateEnd.Value.Date" part. 现在我的a.AGG_DateEnd是一个可以为空的日期时间,只要列表中有空值,我就会因为“a.AGG_DateEnd.Value.Date”部分而得到异常。
But the thing is, the a.AGG_DateEnd also contains hours and minutes, but I do not want this causes my comparison to give unreliable results. 但问题是,a.AGG_DateEnd还包含小时和分钟,但我不希望这导致我的比较给出不可靠的结果。
What can I do to improve? 我该怎么做才能改善?
Thank you, 谢谢,
A quick hack is: 一个快速的黑客是:
a.AGG_DateEnd.GetValueOrDefault().Date >= SelectedFrom
This is OK because the default(DateTime)
(which equals its own .Date
) is not greater than any (other) DateTime
value. 这没关系,因为default(DateTime)
(等于它自己的.Date
)不大于任何(其他) DateTime
值。
Otherwise the usual thing to do is: 否则通常要做的是:
a.AGG_DateEnd.HasValue && a.AGG_DateEnd.Value.Date >= SelectedFrom
where the double &
ensures short-cut evaluation. 双重&
确保快捷评估。
Addition after comments: 评论后补充:
If you want the opposite answer in the case where it is null
, it is: 如果你想要相反的答案,如果它是null
,它是:
(a.AGG_DateEnd ?? DateTime.MaxValue).Date >= SelectedFrom
respectively: 分别:
!a.AGG_DateEnd.HasValue || a.AGG_DateEnd.Value.Date >= SelectedFrom
Later edit: Since C# 6.0 (July 2015), you can use the ?.
稍后编辑:自C#6。0(2015年7月)以来,您可以使用?.
operator instead. 而不是运营商 So use the shorter code: 所以使用更短的代码:
a.AGG_DateEnd?.Date >= SelectedFrom
which will (formally, at least) compare two nullable values of type DateTime?
将(正式地,至少)比较DateTime?
类型的两个可空值DateTime?
. 。 When either operand is "null" (ie .HasValue
gives false
), such a comparison gives false
. 当任一操作数为“null”(即.HasValue
给出false
)时,这样的比较会给出false
。
If you want the opposite bool result in case of null, that is: 如果你想在null的情况下得到相反的bool结果,那就是:
!(a.AGG_DateEnd?.Date < SelectedFrom)
Observe how x >= y
is different from !(x < y)
when we use these lifted operators that operate on Nullable<>
values. 当我们使用运算Nullable<>
值的这些提升运算符时,观察x >= y
与!(x < y)
不同之处。 Any lifted operator (like >=
or <
) will return false
immediately if one of x
and y
is null; 如果x
和y
为空,则任何提升的运算符(如>=
或<
)将立即返回false
; only if both x
and y
are non-null, will they be unwrapped and the contents compared with the non-lifted operator whose return value will be used. 只有当x
和y
都是非空时,才会将它们展开 ,并将内容与将使用其返回值的非提升运算符进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.