C# Linq Where Date Between 2 Dates

C# Linq Where Date Between 2 Dates

Just change it to

var appointmentNoShow = from a in appointments
from p in properties
from c in clients
where a.Id == p.OID &&
(a.Start.Date >= startDate.Date && a.Start.Date <= endDate)

c# query data between dates

Use endDateForFilter >= x.TargetCompletionDate instead. Since you want the field to be greater than the start and less than the end, you should reverse the condition or the operands, not both. Otherwise you end up asking for a date that's after the end.

The condition should look like this:

x.TargetCompletionDate >= startDateForFilter && 
endDateForFilter >= x.TargetCompletionDate

This really looks weird and is way to easy to get wrong without noticing. I got this wrong the first time I typed the condition.

It's better to rewrite it so it's clear what's going on. Either use the same operand order, or rewrite the query so it reads like the actual requirement, eg:

x.TargetCompletionDate >= startDateForFilter && 
x.TargetCompletionDate <= endDateForFilter

or

startDateForFilter <= x.TargetCompletionDate  && 
x.TargetCompletionDate <= endDateForFilter

I prefer the last option, because it looks like the actual logical condition, start <= created && created <= end. It's easier to see that something's wrong this way

Get count of date occurrence between 2 dates using LINQ

Treating strings as dates, like in your code, is not optimal.

The below code uses dates rather than strings, and uses the same basic structure as your current code. It would require 12 queries though (one per month).

var currYear = DateTime.Now.Year;

for (int month = 1; month <= 12; month++)
{
var firstOfThisMonth = new DateTime(currYear, month, 1);
var firstOfNextMonth = firstOfThisMonth.AddMonths(1);

var totalSMS = (from x in db.Messages
where x.MessageDate >= firstOfThisMonth && x.MessageDate < firstOfNextMonth
select x).Count();
}


Related Topics



Leave a reply



Submit