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
Wpf Binding - Default Value for Empty String
How Is the Boxing/Unboxing Behavior of Nullable<T> Possible
Convert Time Span Value to Format "Hh:Mm Am/Pm" Using C#
Unity3D Ui, Calculation for Position Dragging an Item
Formatting Datetime in ASP.NET Core 3.0 Using System.Text.JSON
Is CSV with Multi Tabs/Sheet Possible
Variable Declarations Following If Statements
Is There an Exponent Operator in C#
How to Convert String to Integer in C#
How to Split a Number into Individual Digits in C#
Performance Cost of 'Try' in C#