Reputation: 469
I am having (most likely a trivial problem) with the strings comparison in C#
I am running this LINQ query
var result = from q in Table
where q.ValueDate.ToString() == "12/11/2014 12:00:00 AM"
select q;
and get an empty response
However, when I try
foreach (var i in Table)
{
Console.WriteLine(i.ValueDate.ToString());
}
I get
12/11/2014 12:00:00 AM
12/11/2014 12:00:00 AM
12/11/2014 12:00:00 AM
12/11/2014 12:00:00 AM
What am I doing wrong here?
Upvotes: 2
Views: 665
Reputation: 62488
You can use DateTime
object instead of doing string Comparisons:
DateTime filter = new DateTime(2014,12,11);
var result = from q in Table
where q.ValueDate == filter)
select q
or try specifying your date format:
var result = from q in Table
where q.ValueDate.ToString("dd/MM/yyyy hh:mm:ss tt") == "12/11/2014 12:00:00 AM"
select q;
Upvotes: 0
Reputation: 107267
I wouldn't sacrifice the type safety of a Date by converting it to a string - what is possibly happening is that the ToString()
is being converted to a *Char type via CAST
/ CONVERT
in the DB, which results in a different format. Here's how I would do it:
var checkDateTime = new DateTime(2014, 11, 12);
var result = from q in Table
where q.ValueDate == checkDateTime
select q;
Upvotes: 3