C# Linq Where Date Between 2 Dates - c#

I'm trying to get my linq statement to get me all records between two dates, and I'm not quite sure what I need to change to get it to work: (a.Start >= startDate && endDate)
var appointmentNoShow =
from a in appointments
from p in properties
from c in clients
where a.Id == p.OID && (a.Start.Date >= startDate.Date && endDate)

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)

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

var QueryNew = _context.Appointments.Include(x => x.Employee).Include(x => x.city).Where(x => x.CreatedOn >= FromDate).Where(x => x.CreatedOn <= ToDate).Where(x => x.IsActive == true).ToList();

So you are scrolling down because the Answers do not work:
This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)
1- Data Type in Database is "datetime" and "nullable" in my case.
Example data format in DB is like:
2018-11-06 15:33:43.640
An in C# when converted to string is like:
2019-01-03 4:45:16 PM
So the format is :
yyyy/MM/dd hh:mm:ss tt
2- So you need to prepare your datetime variables in the proper format first:
Example 1
yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")
Example 2 - Datetime range for the last 30 days
DateTime dateStart = DateTime.Now.AddDays(-30);
DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);
3- Finally the linq query you lost your day trying to find (Requires EF 6)
using System.Data.Entity;
_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();
To take time comparison into account as well :
(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)
Note the following method mentioned on other stackoverflow questions and answers will not work correctly:
....
&&
(
s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();
if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:
DatabaseCreatedAtItemThatWeWant = 2018/12/05
startDate = 2018/12/01
EndDate = 2019/01/04
the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail
And in case you have really big data you would execute Native SQL Query rather than linq
...
... where Shipments.Created_at BETWEEN CAST(#Created_at_from as datetime) AND CAST(#Created_at_to as datetime))
....
Thanks

If someone interested to know how to work with 2 list and between dates
var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

public List<tbltask> gettaskssdata(int? c, int? userid, string a, string StartDate, string EndDate, int? ProjectID, int? statusid)
{
List<tbltask> tbtask = new List<tbltask>();
DateTime sdate = (StartDate != "") ? Convert.ToDateTime(StartDate).Date : new DateTime();
DateTime edate = (EndDate != "") ? Convert.ToDateTime(EndDate).Date : new DateTime();
tbtask = entity.tbltasks.Include(x => x.tblproject).Include(x => x.tbUser).
Where(x => x.tblproject.company_id == c
&& (ProjectID == 0 || ProjectID == x.tblproject.ProjectId)
&& (statusid == 0 || statusid == x.tblstatu.StatusId)
&& (a == "" || (x.TaskName.Contains(a) || x.tbUser.User_name.Contains(a)))
&& ((StartDate == "" && EndDate == "") || ((x.StartDate >= sdate && x.EndDate <= edate)))).ToList();
return tbtask;
}
this my query for search records based on searchdata and between start to end date

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.
DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);
var itemsFiltered = allItems.Where(x=>
(x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
(x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
(intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
(intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

I had a problem getting this to work.
I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.
this is my solution:
var yesterday = DateTime.Today.AddDays(-1);
var today = DateTime.Today;
var tomorrow = DateTime.Today.AddDays(1);
var vm = new Model()
{
Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
};

You can use DbFunctions.TruncateTime(StartDateTime) To remove the time from datetime
var appointmentNoShow =
from a in appointments
from p in properties
from c in clients
where a.Id == p.OID && (DbFunctions.TruncateTime(a.Start) >= DbFunctions.TruncateTime(startDate) && endDate)

Related

Filter data on the basis of selected days of the week using LINQ C#

I need to write a query to filter data on the basis of selected date range and days
Query:-
Expression<Func<Task, bool>> filterPredicate =
s => s.Active && !s.Deleted && s.StartDateTime != null && s.EndDateTime != null &&
s.StartDateTime >= startDate && s.StartDateTime <= endDate;
The selected Date range filter is working fine but I need help to filter data if a user has selected days of the week e.g Monday, Tuesday along with the date range
It's something like this... You should know if this addictional condition is and/or and know if startDate and endDate has the same value.
Supposing that StartDateTime is a DateTime type.
Expression<Func<Task, bool>> filterPredicate =
s => s.Active && !s.Deleted && s.StartDateTime != null && s.EndDateTime != null &&
s.StartDateTime >= startDate && s.StartDateTime <= endDate || s.StartDateTime.DayOfWeek == selectedDayOfWeek && s.StartDateTime.DayOfWeek == selectedDayOfWeek;

How to set date between AM/PM 24-hour

I have 2 parameters. one is defaultFromD and another is defaualtToD. if I give 2 date range for this x.CreatedOn >= defaultFromD && x.CreatedOn <= defaultToD
x.CreatedOn >= '2021-10-17' && x.CreatedOn <= '2021-10-20'
its working. but if I give same date for this two parameters this condition is not working.
x.CreatedOn >= '2021-10-20' && x.CreatedOn <= '2021-10-20'
I want to knw how to pass this 2 logic in one condition. Please help me to resolve this issue.
Thank you...
public ResponseDTO<IQueryable<LabRequestForLabOrderDTO>> GetApprovedLabRequestsQueryable(DateTime defaultFromD, DateTime defaultToD)
{
var resp = ResponseBuilder.Build<IQueryable<LabRequestForLabOrderDTO>>();
var reqs = this.labRequestRepository.GetAllActive().Where(x => x.IsActive && x.TrxStatus == 1 && x.InvoiceStatus == "Approved"
&& x.CreatedOn >= defaultFromD && x.CreatedOn <= defaultToD)
.Select(x => new LabRequestForLabOrderDTO
{
Clinic = x.Clinic,
LabOrderCreated = x.LabOrderCreated,
InvoiceStatus = x.InvoiceStatus,
CreatedOn = x.CreatedOn
}).AsQueryable();
resp.AddSuccessResult(reqs);
return resp;
}
Try this
x.CreatedOn.AddDays(-1) > defaultFromD && x.CreatedOn.AddDays(1) < defaultToD
This is due to DateTime and Date Formate.
You should try the following way.
Consider you column CreatedOn datatype is: DateTime
x.CreatedOn.Date >= '2021-10-20' && x.CreatedOn.Date <= '2021-10-20'
This work for me
var todate = defaultToD.AddDays(1);
x.CreatedOn >= defaultFromD && x.CreatedOn <= todate

Conditional if statement inside where in Linq

I have the following SQL query to be translated to LINQ
string qWhere;
DateTime startDate = DateTime.Parse("2018-02-01");
DateTime endDate = DateTime.Parse("2018-02-03");
if(manual == true)
{
qWhere = " deliveryDate>=" + startDate + " and deliveryDate<=" + endDate;
}
else
{
qWhere = "deliveryDate>=" + DateTime.Now;
}
string sqlQuery = "select * from LoadingOrder where " + qWhere;
can anyone help me to translate this query to LINQ, table LoadingOrder have million rows.
Many thanks
If it was just the one condition then you could have two separate queries instead of one query. I think that's a lot easier to read and follow then placing the conditional inside the query itself.
var now = DateTime.Now;
if(manual)
result = LoadingOrders.Where(s=> s.deliveryDate >= startDate && s.deliveryDate <= endDate);
else
result = LoadingOrders.Where(s=> s.deliveryDate >= now);
Suppose the query has lots of conditions and the "delivery date" condition is the only one that changes. In that case you probably wouldn't want to have two entire versions of the query with just one difference. In that case, you can create that one condition separately.
To do that you would create a Func<LoadingOrder, bool> - a function that takes a LoadingOrder and returns true or false. And then you would assign whichever condition you want to check for to that function.
Func<LoadingOrder, bool> deliveryDateCondition;
if(manual)
deliveryDateCondition = loadingOrder =>
loadingOrder.deliveryDate >= startDate && loadingOrder.deliveryDate <= endDate;
else
{
var now = DateTime.Now;
deliveryDateCondition = loadingOrder => loadingOrder.deliveryDate >= now;
}
Now deliveryDateCondition is function that takes a LoadingOrder and returns true or false. You can add that function into your LINQ query, and it works regardless of which function was selected.
var result = LoadingOrders.Where(loadingOrder => deliveryDateCondition(loadingOrder)
&& ...some other condition...
&& ...some other condition...);
Something like this:
DateTime startDate = DateTime.Parse("2018-02-01");
DateTime endDate = DateTime.Parse("2018-02-03");
bool manual = ...;
loadingOrders.Where(
o => o.DeliveryDate >= startDate &&
o.DeliveryDate <= endDate &&
manual ||
o.DeliveryDate >= DateTime.Now &&
!manual);
var now = DateTime.Now;
var query = from e in db.LoadingOrder
where (e.deliveryDate >= startDate && e.deliveryDate <= endDate && manual)
|| (e.deliveryDate >= now)
select e;
OR
var query = db.LoadingOrder.Where(x => (x.deliveryDate >= startDate && x.deliveryDate <= endDate && manual) || (x.deliveryDate >= now));

Use LINQ to compare the date part of DateTime

I want to filter some documents between a different date. First I tried comparing the dates directly, but the time (hour, minutes, second) doesn't have to be considered. Therefore only the date part is needed, but the following approach is wrong:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year >= fromDate.Value.Year
&& d.LastModifiedAt.Value.Month >= fromDate.Value.Month
&& d.LastModifiedAt.Value.Day >= fromDate.Value.Day);
}
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year <= toDate.Value.Year
&& d.LastModifiedAt.Value.Month <= toDate.Value.Month
&& d.LastModifiedAt.Value.Day <= toDate.Value.Day);
}
Consider the from date 8/15/2014 12:00:00 AM and the to date 9/15/2014 12:00:00 AM. If the document has the date 8/16/2014 10:06:25 AM it won't be in the results. The reason is that I directly compare each component (year, month, day). Because the day is 16 and 16 > 15 the last condition is not met.
How can I solve this? Should I set the time to one minute before midnight? Or should I calculate the difference?
Just use the DateTime.Date property:
if (fromDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date >= fromDate.Value.Date);
}
if (toDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date <= toDate.Value.Date);
}
DateTime has a Date property which returns a DateTime for the same day at midnight:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date >= fromDate.Value.Date);
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date <= toDate.Value.Date);

Date range overlap issue in LINQ

Given date range in Table for particular record say for particular feild "Name"
If some one trying to insert that Name within previous date range interval then it should not be allowed.
I have tried here some code look at this ...
if (dataContext.TableAs.Where(
x => x.EndDate > StartDate &&
x.Name == Name).Count() == 0)
{
//insert record
}
but is not successful all times.
Can anyone suggest what I have missing over here ?
I have tried below query in SQL , how can I use that in LINQ for above code
SELECT COUNT(*) FROM TableA WHERE ('2012-04-02' between StartDate and EndDate or '2012-08-28'
between StartDate and EndDate or StartDate between '2012-04-02' and '2012-08-28' or EndDatebetween '2012-04-02' and '2012-08-28' ) and Name='Test'
try this;
if (dataContext.TableAs
.Where(x => x.Name == Name)
.Max(x => x.EndDate) < StartDate)
EDIT - For second part of question
DateTime Date1 = new DateTime("2012-04-02");
DateTime Date2 = new DateTime("2012-08-28");
var query = (dataContext.TableAs
.Where(x => x.Name == "Test")
.Where(x => (x.StartDate >= Date1 && Date1 <= x.EndDate)
|| (x.StartDate >= Date2 && Date2 <= x.EndDate)
|| (Date1 >= x.StartDate && x.StartDate <= Date2)
|| (Date1 >= x.EndDate && x.EndDate <= Date2))).Count();
var StartDate = new DateTime(2012,04,02);
var EndDate = new DateTime(2012,08,28);
var Name = "Test";
if (!dataContext.TableAs.Any(
x=> x.Name == Name && x.EndDate >= StartDate && x.StartDate <= EndDate
)
{
//insert record
}

Categories

Resources