简体   繁体   English

ADO.NET 实体框架:在 Where/OrderBY 中将字符串转换为 Int

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

I am writing a LINQ query against the ObjectContext.我正在针对 ObjectContext 编写 LINQ 查询。 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):我在 LINQ 到实体中基本上需要做的是(我知道这行不通,但我这样做是为了说明):

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:我假设“key”是一个变量 int,因此使用 ToString() 将其转换为字符串,并使用它与 KeyAsString 进行比较,并且按不使用转换的顺序:

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.如果您使用ToList()ToArray()之类的方法将结果提取到 memory 中,您将能够转换为 int 或使用自定义比较器。

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM