Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing dates when date my be null

Tags:

c#

linq

I am trying to get all dates in a Linq query between StartDate and EndDate. Both my StartDate and EndDate are the right dates, but my results are inconsistent. Everything else in the query works, just not the comparison of the dates. What am I doing wrong?

where (startDate == null || DateTime.Compare((DateTime)startDate,
o.FirstAirDate) < 0) && (endDate == null|| DateTime.Compare(
o.FirstAirDate, (DateTime)endDate) > 0)

Dates are showing up outside of the range and when I move the dates closer together nothing appears. For example If I search from December 21-26 I get results between those two dates but also a date for the 27th shows up. If I search from December 23-26 nothing shows up, even though I saw dates in this range show up when I searched from December 21-26

like image 999
Aaron Avatar asked Jan 06 '23 23:01

Aaron


1 Answers

If you're trying to get all instances where FirstAirDate is between startDate and endDate (and either startDate or endDate can be null) and they are all DateTime objects you might want to try something like:

var objects = MyObjectsList.Where(o => 
     (!startDate.HasValue || o.FirstAirDate >= startDate.Value) 
  && (!endDate.HasValue || o.FirstAirDate <= endDate.Value))

You can compare dates with simple comparison operators, just have to use the .Value for the nullable DateTime properties when doing the comparison - in which case it's best to null check first.

like image 79
Bardicer Avatar answered Jan 18 '23 08:01

Bardicer