132k views
2 votes
How to compare two dates in linq query without time?

1 Answer

2 votes

Final answer:

To compare two dates in a LINQ query without considering the time component, utilize the Date property or functions like DbFunctions.TruncateTime in Entity Framework to focus solely on the date part.

Step-by-step explanation:

When comparing two dates in a LINQ query without the time component, you can use the Date property of a DateTime object to ignore the time part. The following is an example of how you might perform such a comparison:

var result = from e in context.Entities
where e.StartDate.Date == e.EndDate.Date
select e;

This LINQ query finds all entities where the StartDate and EndDate are on the same day, disregarding the time of day. In Entity Framework, the SQL generated will use the appropriate database functions to compare the date part only. Alternatively, you can also use the DbFunctions.

TruncateTime method in Entity Framework to explicitly remove the time part from a DateTime object before comparison.

User Rajat Saxena
by
7.5k points