Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 263
Brian Mains Avatar asked Jan 28 '26 13:01

Brian Mains


2 Answers

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.

like image 151
Juan Ayala Avatar answered Jan 30 '26 01:01

Juan Ayala


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; 
like image 41
Aducci Avatar answered Jan 30 '26 02:01

Aducci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!