检查数据表列中是否包含数值 [英] Check datatable column contains numeric values

查看:44
本文介绍了检查数据表列中是否包含数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想查找那些包含数值的行表格,因此我按照以下步骤进行操作

I want to find only those row form table which contains numeric values , so for that I did as following

dtDetails.Select(" (ISNUMERIC(OriginatingTransit)=0)")

但是会引发异常

The expression contains undefined function call ISNUMERIC().

推荐答案

您必须在数据库级别执行此操作,或者循环遍历自己并编写一些检查值是否可以解析为数字的操作.Select方法不支持您要执行的操作:

You'll have to do that at the database level, or loop through yourself and write something that checks if a value can be parsed into a number. The Select method does not support what you're trying to do: Expression property on MSDN, contains info about what's supported.

bool IsNumeric(object o)
{
  decimal result_ignored;
  return o != null && 
    !(o is DBNull) && 
    decimal.TryParse(Convert.ToString(o), out result_ignored);
}

然后您可以执行以下操作:

And then you can do something like this:

var filtered = dtDetails.Rows.Cast<DataRow>().
  Where(r => IsNumeric(r["OriginatingTransit"]));

如果您随后枚举 filtered ,则只会得到该列中具有数字值的那些.

If you then enumerate filtered, you will get only those with numeric values in that column.

这不是完美的-因为某些评论在与之相关的答案中提到由Surjit Samra在对您的上述问题的评论中,是数字"的确切含义不明确.我认为,这是通过使用 decimal 尝试解析值来进行最广泛的描述.如果您的要求比较严格,则可以使用其他类型(例如 int float )或正则表达式.

This isn't perfect - because as some comments mention on the answer linked to by Surjit Samra in the comments to your question above, the exact meaning of 'is numeric' is loose. This goes for the widest possible description, I think, by using decimal to attempt to parse the value. You could use a different type (e.g. int or float), or a regular expression, perhaps, if your requirements are tighter.

这篇关于检查数据表列中是否包含数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆