【问题标题】:How to check if column can be converted to double? (DataTable.Column.DataType)如何检查列是否可以转换为双精度? (DataTable.Column.DataType)
【发布时间】:2013-04-19 06:14:19
【问题描述】:

我需要简单的条件来替换这个(不完整的)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

【问题讨论】:

标签: c# if-statement types


【解决方案1】:

你可以试试这个:

if(Microsoft.VisualBasic.Information.IsNumeric
    (
     Activator.CreateInstance(col.DataType
    )
   )

【讨论】:

    【解决方案2】:

    您也可以查看DataColumn.DataType.Name 属性。喜欢:

    string[] IntType ={"Byte","Decimal","Double","Int16","Int32","SByte",
                    "Single","UInt16","UInt32","UInt64"};
    
    static void Main(string[] args)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("num", typeof(int));
        dt.Columns.Add("str", typeof(string));
        Program p=new Program();
        string type = dt.Columns["num"].DataType.Name;
        if (p.IntType.Contains(type))
        {
            //True
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      您可以像以前一样使用 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.
      }
      

      【讨论】:

      • 所以没有专门的方法,我需要所有可能类型的列表。谢谢。
      • @Kamil 我认为这个link 提供了一个更具可读性的解决方案
      • 是的,您必须使用DataType 属性。您还可以检查类型是否为double?(可为空),有时您的列可以具有空值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2020-06-02
      • 1970-01-01
      • 2015-04-11
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多