开发者

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

开发者 https://www.devze.com 2023-03-28 09:53 出处:网络
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):

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; 
0

精彩评论

暂无评论...
验证码 换一张
取 消