-->

Comparing two dates in LINQ to SQL

2020-07-30 03:43发布

问题:

I have a database with a table named meeting. 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? How does the comparison take place?

I am using SQL Server 2008 and LINQ to SQL queries.

回答1:

Something like this

DateTime start = new DateTime("4/25/2011");
DateTime end = new DateTime("5/2/2011");
var result = db.Meeting.Where(d => d.MeetingDate >= start 
                 && d.MeetingDate <= end);


回答2:

Query style:

from m in db.Meetings
where m.Start => start && m.End <= end
select m;

Method style:

db.Meetings.Where(m => m.Start => start && m.End <= end);