Reputation: 1
I have to do a c# search on records in an array from a sql server db
using 3 data elements. One of the data elements has to be a DateTime element in a column called DateOfBirth. Unfortunately there are a lot of null values in this column and I can't figure out how to compare a DateTime variable to a field with NULL
values. I see a lot of answers that appear to be close to what I need here, but nothing has helped. Thanks for any help, This has been my format.
if ((DateTime)dt == (DateTime)temp[i].Individual.DateOfBirth)
GlobalNum3.bnum3 = 1;
Upvotes: 0
Views: 123
Reputation: 43254
I'm assuming that dt
is already a DateTime
, in which case it can't be null (DateTime
is a struct
) and there's no need to cast it.In addition, either temp[i].Individual.DateOfBirth
is a DateTime
too and so cannot be null
either, or it's a Nullable<DateTime>
.
Assuming both are DateTimes
, DB nulls
will be set to DateTime.MinValue
, so just compare the values:
if (dt == (DateTime)temp[i].Individual.DateOfBirth)
{
GlobalNum3.bnum3 = 1;
}
However, if temp[i].Individual.DateOfBirth
is a Nullable<DateTime>
, it might be null
, or might simply have no value, so use it like this:
var possibleDateOfBirth = temp[i].Individual.DateOfBirth;
if (possibleDateOfBirth != null &&
possibleDateOfBirth.HasValue &&
dt == possibleDateOfBirth.Value)
{
GlobalNum3.bnum3 = 1;
}
Upvotes: 1
Reputation: 12847
If you are querying the DB then try testing the nullable .HasValue
property like this:
if (temp[i].Individual.DateOfBirth.HasValue && dt == temp[i].Individual.DateOfBirth.Value)
{
GlobalNum3.bnum3 = 1;
}
Obviously I'm assuming you are testing DateTime?
properties.
Upvotes: 0