简体   繁体   中英

Using int.parse(string) in linq search doesn't work

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.

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;

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.

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.

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

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