Linq. Date Range

S

shapper

Hello,

I am getting a list of objects where each object has 2 properties:
StartDate and FinishDate.

I want to select only the items where DateTime.Now is in range ...

But following the next rules:
1. DateTime.Now > StartDate if only StartDate is defined
2. DateTime.Now < FinishDate if only FinishDate is defined
3. StartDate < DateTime.Now < FinishDate if only FinishDate is defined

If both dates are undefined then select the record no matter what ...

Is this possible?

I think I might to something in my Linq expression as follows:

....
where Check(StartDate, FinishDate) == true

Where Check would be a function to do the testing ...

Is this the way to go?

Thanks,
Miguel
 
M

Marc Gravell

I think I might to something in my Linq expression as follows:
...
where Check(StartDate, FinishDate) == true
Is this the way to go?

If you are only using LINQ-to-objects, then fine. If you are using
LINQ-to-SQL, then you can get a UDF to do the same by exposing the UDF
in the data-context [as composable] (although it might not necessarily
make good use of indexing) - but Entity Framework doesn't support this
usage.

Personally I'd do it long hand:

where (row.StartDate == null || row.StartDate < when)
&& (row.FinishDate == null || row.FinishDate > when)

That should work in any framework (assuming that StartDate and
FinishDate are DateTime?).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top