C# 在表中,列数据类型为varchar,使用linq to sql仅检索列中的数字/数字值
我有一个数据类型为C# 在表中,列数据类型为varchar,使用linq to sql仅检索列中的数字/数字值,c#,sql,linq,entity-framework,C#,Sql,Linq,Entity Framework,我有一个数据类型为varchar的表。我只需要从列中检索那些纯数字的值。为此,我使用了如下所示的Linq查询,它只检查小写字母。它将无法检查此@-1234。我提供了我想要做的细节 | input | | expected output | | @!qw1 | | 12345 | | 12345 | | 90345 | | ab567 | | 90345 | |
varchar
的表。我只需要从列中检索那些纯数字的值。为此,我使用了如下所示的Linq查询,它只检查小写字母。它将无法检查此@-1234
。我提供了我想要做的细节
| input | | expected output |
| @!qw1 | | 12345 |
| 12345 | | 90345 |
| ab567 |
| 90345 |
| 123-q |
代码:
您可以使用
long.TryParse
检查数值
pricingdemoEntities price = new pricingdemoEntities();
long num;
var money= (from demos in price.demotables
where long.TryParse(demos.value.ToString(),out num)
select demos.value).ToList();
foreach (var final in money)
请看下面的例子,也许这会帮助你
string[] stringList = { "123", "xsd", "%Vhh", "123H", "5841" }; // just an array of strings
var a = stringList.Where(x => x.All(char.IsDigit)); // checking for digits and returning them
我希望这将对您有所帮助:)这些查询不能通过实体框架转换为SQL,因此一个选择是首先实现您的结果。这不是很有效,但您可以通过限制查询中返回的内容来改进它。然后对结果执行数字检查 例如:
var acceptable = ".,0,1,2,3,4,5,6,7,8,9"; // list of acceptable values
var nums = acceptable.Split(',').Select(a=> a[0]); // get the chars
using(var price = new pricingdemoEntities())
{
// You can limit this even further by adding a take or additional where clauses
var query = price.demotables.Select(p => p.value).AsEnumerable();
var money = query.Where(q=> q.value.All(c=> nums.Contains(c)).ToList();
}
您可以使用扩展方法
using System.Data.Entity.SqlServer;
var money = (from demos in price.demotables
where SqlFunctions.IsNumeric(demos.value) == 1
select demos.value).ToList();
试试这个
price.demotables.Where(x=>SqlFunctions.IsNumeric(x.Data)==1).ToList()
与其指定使值不是数字的每个字符,不如只指定值是数字时才需要它 因此,在原始SQL中,可能会出现如下情况:
SELECT val
FROM table
WHERE ISNUMERIC(val) = 1
var money = (
from demos in price.demotables
where SqlFunctions.IsNumeric(demos.value) == 1
select demos.value).ToList();
在实体框架中
可以使用简便的方法创建类似的查询
在您的情况下,它看起来像这样:
SELECT val
FROM table
WHERE ISNUMERIC(val) = 1
var money = (
from demos in price.demotables
where SqlFunctions.IsNumeric(demos.value) == 1
select demos.value).ToList();
long.TryParse(demos.value.ToString(),out num)
在linq中不起作用。你能把你正在尝试的代码传给我吗。。由于我尝试的上述代码工作正常。@HiteshMistry您的代码不是linq to entities。用类似于OP代码的东西尝试同样的方法。这只是一个例子,您只需使用linq到列表或数组中的实体获取数据,然后使用我代码的第二行。哇!不知道SqlFunctions!Thanks@reckface,可以找到其他有趣的扩展,并