getting date from nullable datetime ?

c#, linq

Solution

Well, if you already know it's non-null, you can use `Value` to get the underlying non-nullable value:

q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value.Date < DateTime.Now.Date)
     .ToList();

Or if you want to filter on that too:

q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value != null &&
                 c.CallNextDate.Value.Date < DateTime.Now.Date)
     .ToList();

I'd strongly encourage you to fetch today's date once though, and reuse it for the whole query:

var today = DateTime.Today;
q = q.AsQueryable()
     .Where(c => c.CallNextDate.Value != null &&
                 c.CallNextDate.Value.Date < today)
     .ToList();

That will give you more consistency. You should really consider whether you definitely want the system local date, by the way.

(Do you definitely need to use `AsQueryable`, by the way? That's relatively rare.)

Problem

I have declared a field in my model as nullable datetime like this ``` public DateTime? CallNextDate {get;set;} ``` in my aspx code behind I am using this linq like this: ``` q = q.AsQueryable() .Where(c => c.CallNextDate.Date < DateTime.Now.Date ) .ToList(); ``` but `c.CallNextDate.Date` is not available. Please suggest how to fix it

Original source