简体   繁体   中英

ADO.NET Entity Framework: Converting String to Int in Where/OrderBY

I am writing a LINQ query against the ObjectContext. What I essentially need to do in LINQ to Entities is this (I know this won't work, but I'm doing it this way to illustrate):

from c in context.Table
where key == int.Parse(c.KeyAsString)
order by int.Parse(c.KeyAsString)
select c

I wasn't sure if this was possible... anybody know of a way?

Thanks.

try it the other way around. I assume "key" is a variable int so cast that to string by using ToString() and use that to compare with KeyAsString and in the order by don't use a cast:

var keyString = key.ToString();
var query = from c in context.Table
where keyString == c.KeyAsString
order by c.KeyAsString
select c

if you have trouble with the order by use a method like ToList() or ToArray() to pull the results into memory and there you'll be able to cast to int or use a custom comparer.

This is not the cleanest looking solution, but it will work as long as all your strings are valid integers. This can be used with doubles as well

var query = from c in context.Table
            let IntOrder = context.Table.Take(1).Select(x => c.KeyAsString).Cast<int>().FirstOrDefault()
            where IntOrder == key
            orderby IntOrder
            select c; 

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