Reputation: 43
I'm using LINQ search in C#. One of my searches require converting a string
to an int
.
When I try to use int.parse()
or convert.toInt32()
, it displays an error (not recognized in LINQ)
for example:
var google = from p in ctx.dates
where int.Parse(p.effDate) < 20101212 && int.Parse(p.effDate) > 20121212
select p;
as you can see I have a string that contains my date in yyyymmdd
format and I want to convert it to an integer so I can search between those date.
Upvotes: 0
Views: 331
Reputation: 43
finaly i've found a decent answer :
google = from p in ctx.dates
where p.effDate.CompareTo(picker1) > 0 && p.effDate.CompareTo(picker2) <0
select p;
picker1 and picker2 are both strings in "yyyymmdd" thank you all for helping me
Upvotes: 0
Reputation: 838666
The yyyyMMdd
format has a nice property that the lexicographical ordering is the same as the chronological ordering so you can use string comparisons:
var google = from p in ctx.dates
where p.effDate.CompareTo("20121212") < 0
&& p.effDate.CompareTo("20101212") > 0
select p;
Upvotes: 8
Reputation: 16413
That's because int.Parse
is a client call, the Linq provider doesn't know how to map that to a database function.
Since the string is in an easily sorted format, you can use where p.effDate < "20101212" && p.effDate > "20121212"
.
A better approach would be to change the database to store the dates in date
columns not char
or varchar
columns.
Upvotes: 0
Reputation: 13043
As first you can't compare dates by just converting them to int, because it will fail in most cases. Parse your strings using DateTime
Parse
or ParseExact
and compare them.
Upvotes: 1