Caverman
Caverman

Reputation: 3727

Linq query on a Date giving an error "Nullable object must have a value."

I have a list of objects that I'm passing into a function where I want to filter out records for a specific company and if a DateTime field is today.

I'm getting an error "Nullable object must have a value." when I do and I believe it is due to the fact that some of the "Verified_Date" fields are null, but not all of them.

This is the LINQ I came up with. Is there a way that I can filter out on a specific company and if there Verified_Date = today even if some of the records have a Verified_Date = NULL?

var today = DateTime.Today;
var listFiltered = data.Where(d => d.CompanyCode == companyCode && d.VerifiedDate.Value.Date == today).ToList();

Upvotes: 0

Views: 163

Answers (2)

yinnonsanders
yinnonsanders

Reputation: 1871

Check that VerifiedDate isn't null in your Where condition.

var listFiltered = data.Where(d => d.CompanyCode == companyCode
                                && d.VerifiedDate != null
                                && d.VerifiedDate.Value.Date == DateTime.Today)
                       .ToList();

Upvotes: 1

ocuenca
ocuenca

Reputation: 39376

You can try this:

var today = DateTime.Today;
var listFiltered = data.Where(d => d.CompanyCode == companyCode 
                                && d.VerifiedDate!=null
                                && d.VerifiedDate.Value.Date == today).ToList();

Upvotes: 1

Related Questions