开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜