Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does one compare the date part of a nullable datetime in a linq / lambda query?

Tags:

c#

datetime

linq

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.

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.

What can I do to improve?

Thank you,

like image 997
user1841243 Avatar asked Nov 26 '14 08:11

user1841243


1 Answers

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.

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:

(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 ?. operator instead. So use the shorter code:

a.AGG_DateEnd?.Date >= SelectedFrom

which will (formally, at least) compare two nullable values of type DateTime?. When either operand is "null" (i.e. .HasValue gives false), such a comparison gives false.

If you want the opposite bool result in case of null, that is:

!(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. Any lifted operator (like >= or <) will return false immediately if one of x and y is null; 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.

like image 194
Jeppe Stig Nielsen Avatar answered Oct 15 '22 04:10

Jeppe Stig Nielsen