I have a list of objects with a DateTime parameter.
I would like to use LINQ to query this list and return entries by date but ignoring the Time portion
So I would like to select any entry that occurs at any time on 08-10-2012.
You can use this snippet for in-memory queries:
var theDate = new DateTime(2012, 08, 10);
var entriesOnTheDate = list.Where(item => item.DateTimeField.Date.Equals(theDate));
For querying against SQL Server data source, you can use SqlFunctions.DatePart
to extract the day, the month, and the year, and compare them separately.
var entriesOnTheDate = dbContext
.EntriesWithDateTimeField
.Where(item => SqlFunctions.DatePart("Year", item.DateTimeField) == 2012
&& SqlFunctions.DatePart("Month", item.DateTimeField) == 8
&& SqlFunctions.DatePart("Day", item.DateTimeField) == 12);
entries.Where( e => e.Property.Date == new DateTime( 2012, 08, 10 ) )
You can add a range of times that covers your entire day:
entries.Where(e => e.Property.Date >= new DateTime(2012, 08, 10)
&& e.Property.Date < new DateTime(2012, 08, 11));
what about using EntityFunctions.TruncateTime ( EF 6 onwards)
var result = context.Employees
.Where(x => EntityFunctions.TruncateTime(x.LoginDate) ==DateTime.Today)
.FirstOrDefault();
Namespace: System.Data.Objects.EntityFunctions.TruncateTime
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.