Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting date from nullable datetime ?

Tags:

c#

linq

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

like image 692
DotnetSparrow Avatar asked Nov 21 '12 17:11

DotnetSparrow


1 Answers

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.)

like image 160
Jon Skeet Avatar answered Oct 01 '22 17:10

Jon Skeet