Reputation: 101
I'm trying to get results if there are records where the date falls between two fields: start and finish. The linq query I have doesn't seem to return any results:
var alerts = from q in db.AlertMsgs
where (q.Start >= DateTime.Now
&& q.Finish <= DateTime.Now)
select q;
Any suggestions on why this is? I've also tried
var alerts = from q in AlertMsgs.Where(q => q.Start.CompareTo(DateTime.Now) > 0
&& q.Finish.CompareTo(DateTime.Now) < 1)
select q;
without any luck either.
Upvotes: 1
Views: 1169
Reputation: 564441
You have your conditions backwards. Try:
var alerts = from q in db.AlertMsgs
where (q.Start < DateTime.Now && q.Finish > DateTime.Now)
select q;
Or, using the method syntax (and <=
/>=
, in case you want that comparison):
var alerts = db.AlertMsgs
.Where(q => q.Start <= DateTime.Now && q.Finish >= DateTime.Now);
This will give you all messages which have already started (Start < Now
) and have not yet finished (Finish > Now
). What you were searching for was messages which haven't started yet (or started exactly now), but which have already finished (or finished exactly now). This would only return an item which had the same start and end time, and where both times were exactly DateTime.Now
.
Upvotes: 2