简体   繁体   中英

Comparing Dates in LINQ and C#

I have a LINQ query which checks to see if there are any tests done since the beginning of the year.

var MetersTestedCount = (from n in _mttDomainContext.MTTMeterTests
                              where n.TestDate > DateTime.Parse("1/1/2010")  
                              select n.TestDate).Count();

This query however returns an empty set. I have a similar SQL query which pulls some records,

USE MeterTestTracking
Select * From MTTMeterTest
WHERE TestDate > '1/1/2010'

I have been to the previous posts. Even though similar, still no help:

How to compare just the date, not the timestamp using LINQ

and

How to compare dates in LINQ?

What's the correct way to check dates in LINQ to return a dataset?

Have you tried creating a DateTime instance?:

var MetersTestedCount = (from n in _mttDomainContext.MTTMeterTests
                              where n.TestDate > new DateTime(2010,1,1).Date  
                              select n.TestDate).Count();

如何明确说明您正在转换的日期字符串的格式,即使用

DateTime.Parse("1/1/2010", "dd/MM/YYYY")

Run SQL profiler (if you have MS SQL 2005 or higher) and check what queries are executed. Or try Linq2Sql visualizer which shows you generated SQL and/or results.

var query = Set().AsQueryable();
query = query.Where(r => (DateTime)(r.StartDate) > (DateTime)(obj.StartDate));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM