Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select items with Linq by Date while ignoring Time portion of a DateTime property?

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.

like image 277
stephen776 Avatar asked Aug 14 '12 14:08

stephen776


People also ask

How to compare DateTime without time via LINQ?

StartDate >= DateTime. Now). OrderBy(d => d. StartDate);

How do I compare two dates in LINQ query with time?

Meeting dates are stored in this table using the following format: May 2nd 2011 is (for example) formatted as 5/2/2011 . My requirement is to get the meetings between two dates (say, 4/25/2011 and 5/2/2011) and to write a query comparing a date with these two dates. Does it compare like 4/25/2011 < 4/26/2011?

Why from comes before select in LINQ?

The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that's why from clause must appear before Select in LINQ.

What does LINQ Select Return?

By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.


2 Answers

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);
like image 116
Sergey Kalinichenko Avatar answered Nov 15 '22 15:11

Sergey Kalinichenko


 entries.Where( e => e.Property.Date == new DateTime( 2012, 08, 10 ) )
like image 38
Wiktor Zychla Avatar answered Nov 15 '22 15:11

Wiktor Zychla