Jacob Saylor
Jacob Saylor

Reputation: 2381

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?

Upvotes: 1

Views: 9018

Answers (4)

Ashish Kapoor
Ashish Kapoor

Reputation: 121

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

Upvotes: 0

Karel Frajták
Karel Frajták

Reputation: 4489

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.

Upvotes: 0

Thomas
Thomas

Reputation: 64635

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();

Upvotes: 5

Raj
Raj

Reputation: 1770

How about explicitly stating the format of the date string you're converting i.e. use

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

Upvotes: 0

Related Questions