c# - 如何检查列是否可以转换为 double ? (DataTable.Column.DataType)

标签 c# if-statement types

我需要一个简单的条件来替换这个(不完整的)if 条件。

// i dont want to write all possible data types
if (col.DataType == typeof(int) || col.DataType == typeof(int64) ... all types)
{
    // i want to do something on numeric columns
    // (convert all numbers to double datatype)
}
else
{
    // string and other non-numbers will remain unchanged
}

我正在尝试这样的事情:

col.DataType.IsNumeric()

但是那个类中没有这个方法。

我不能对数据使用 TryParse() 方法,因为数据太多了。

条件只能由 DataTable 列数据类型属性确定。

有什么简单的方法可以简化我的if吗?

最佳答案

您可以像以前一样使用 DataType,或者创建一个函数来执行此操作(请参阅 Determine if DataColumn is numeric):

public static bool IsNumeric(this DataColumn col) {

  if (col == null)
    return false;

  // all numeric types
  var numericTypes = new [] { typeof(Byte), typeof(Decimal), typeof(Double),
        typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte),
        typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};

  return numericTypes.Contains(col.DataType);
}

并使用

if (col.IsNumeric()) 
{
   // the column is numeric
}

现在,对于您专栏的内容,您可以尝试使用 double.TryParse() 方法,如下所示:

double temp;
if (double.TryParse(col["Column"].ToString(), out temp))
{
  // the content can be converter and you can read it from temp variable.
}

关于c# - 如何检查列是否可以转换为 double ? (DataTable.Column.DataType),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213265/

相关文章:

c# - 'Object.ReferenceEquals' 始终为 false,因为它是使用值类型调用的

c# - NHibernate 中的子表

php - 在 PHP 中添加额外代码后,If 语句未运行

java - 传递类型参数的类,该类型参数本身可以在 Java 中参数化

c# - 为什么observablecollection初始化为null?

c# - CompilationUnit 对象是否应该具有保存自身并编译到磁盘的方法?

Haskell If 的多个条件

Java:随机生成的零数

matlab - 是否可以在 MATLAB 中强制执行输入参数数据类型?

.net - 可以清除或禁用 .NET MethodInfo 缓存吗?