I am trying to compare date only. The value in table is DateTime with format
2014-01-29 09:00:00.000. Please advise thank you
public static List<vwReportDate> GetDetail(string startDate, string endDate)
{
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate <= dtEndDate
select c;
return query.ToList();
}
It looks like you're using Entity Framework and LINQ to EF. If that's true you can't use DateTime.Date property because it's not supported in LINQ to EF. You have to use EntityFunctions.TruncateTime(myDateTime) static method instead:
var query = from c in entities.vwReportDate
let eventDate = EntityFunctions.TruncateTime(c.EventCreateDate)
where eventDate >= dtStart && eventDate <= dtEndDate
select c;
My approach to this problem, which does not depend on EF, is to use "less than" for the end of the date range (after moving the end of the date range one day forward):
startDate = "2014-01-28";
endDate = "2014-01-28";
DateTime dtStart = Convert.ToDateTime(startDate);
DateTime dtEndDate = Convert.ToDateTime(endDate).AddDays(1);
var entities = new DataEntiies();
var query = from c in entities.vwReportDate
where c.EventCreateDate >= dtStart && c.EventCreateDate < dtEndDate
select c;
return query.ToList();
Question: why do you ignore the argument values provided by the method's caller?
Use the Date property of a DateTime struct to retrieve the "date" part.
Gets the date component of this instance.
Use it in code:
var query = from c in entities.vwReportDate
where c.EventCreateDate.Date >= dtStart && c.EventCreateDate.Date <= dtEndDate
select c;
If you are using Entity framework (as it looks like you do), you'll have to use the EntityFunctions.TruncateTime (helper) method, because otherwise the query can't be converted.
var query = from c in entities.vwReportDate
where EntityFunctions.TruncateTime(c.EventCreateDate) >= dtStart && EntityFunctions.TruncateTime(c.EventCreateDate) <= dtEndDate
select c;
Related
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));
for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& r.Field<DateTime>("SaleDate") == date
select r.Field<int>("SaleValue")).FirstOrDefault();
}
From the above snippet r.Field<DateTime>("SaleDate") == date part throws exception Specified cast is not valid.
date variable and dtSalesData rows have the same value 3/1/2015 12:00:00 AM
Any clue?
UPDATE==================================
Sorry friends, I did a silly mistake here. Problem is in the next line-
select r.Field<int>("SaleValue")).FirstOrDefault(); //Would be <decimal>
Please accept my apology. Thanks to all.
Have you tried doing this?
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& Convert.ToDateTime(r.SaleDate) == date
select r.Field<int>("SaleValue")).FirstOrDefault();
for (DateTime date = fromDate; date <= toDate; date = date.AddDays(1))
{
var bwSalesValue = (from r in dtSalesData.AsEnumerable()
where r.Field<int>("PositionId") == pdPositionId
&& r.Field<DateTime>("SaleDate") == DBNull.Value ? DateTime.MinValue : date);
select r.Field<int>("SaleValue")).FirstOrDefault();
}
Maybe you shouldnt use where clause when SaleDate return DBNull.Value because it can't be convert DateTime to null.
Hello I need to run the following
query and group datetime field only by the date value.
var startDateTime = regDate.Date;
var endDateTime = regDate.AddSeconds(fullDayinSeconds);
var res = from u in ObjectContext.Member.Where(o => o.RegisterTime >= startDateTime && o.RegisterTime <= endDateTime)
group u by new { u.PartnerId, u.RegisterTime.Date, u.partners.Name } into pgroup
let count = pgroup.Count()
select new PartnersUsersInfo
{
PartnerId = pgroup.Key.PartnerId.GetValueOrDefault(0),
PartnerName = pgroup.Key.Name, PartnerUsersAmount = count
};
u.RegisterTime.Date - returns the exception The specified type member 'Date' is not supported in LINQ to Entities.
I have tried to use EntityFunctions.TruncateTime but it is not accepteble for group operations.
how to solve it ?
you can try add temp col with date and group by it
use
db.CallLogs.Where(r => DbFunctions.TruncateTime(r.DateTime) == callDateTime.Date).ToList();
I want to get the today entered records using LINQ to SQL. I wrote the below code but it is returning previous date records also.
DateTime todaysDate = DateTime.Now;
DateTime yesterdaysDate = DateTime.Now.AddDays(-1);
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin > yesterdaysDate && a.singin <= todaysDate)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
Can you please tell me how to get the today entered records only using LINQ to SQL?
Insetad of DateTime.Now use DateTime.Today like:
DateTime startDateTime = DateTime.Today; //Today at 00:00:00
DateTime endDateTime = DateTime.Today.AddDays(1).AddTicks(-1); //Today at 23:59:59
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin >= startDateTime && a.singin <= endDateTime)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
or You can try the following simpler version, (I am not sure if that would translate into SQL)
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin.Date == DateTime.Today)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
How to filter data between two datetime. Here i am filtering the text file length in a directory..I need to filter text file between the selected date.
DateTime startDate = dateTimePicker1.Value;
DateTime endDate = dateTimePicker2.Value;
var queryList1Only = from i in di.GetFiles("*.txt", SearchOption.AllDirectories)
select i.Length;
Any suggestion?
Use the Where clause:
DateTime startDate = dateTimePicker1.Value;
DateTime endDate = dateTimePicker2.Value;
var queryList1Only = from i in di.GetFiles("*.txt", SearchOption.AllDirectories)
where i.GetCreationTime() > startDate && i.GetCreationTime() < endDate
select i.Length;
Instead of GetCreationTime you could use GetLastWriteTime or GetLastAccessTime.
I'd advise checking out a few examples using the where clause for a full understanding of how it all works here.
Well, how about a where clause?
var query = from i in di.GetFiles("*.txt", SearchOption.AllDirectories)
where (i.GetCreationTime() > startDate && i.GetCreationTime() < endDate)
select i.Length;
from fi in new DirectoryInfo(#"c:\path").EnumerateFiles("*.txt")
where fi.CreationTime > startDate and fi.CreationTime < endDate)
select fi.FullName;
this work for me
var data = (from dataperiod in periods where dataperiod.DateStart <= (DateTime)finalDayNovelty && dataperiod.DateEnd >= (DateTime)initialDayNovelty select dataperiod ).ToList();