1

I need simple condition to replace this (incomplete) if condition.

// 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
}

I was trying something like this:

col.DataType.IsNumeric()

but there is no such method in that class.

I cant use TryParse() method on data because there is too much data.

Condition must be determined only by DataTable column datatype property.

Is there any simple method to simplify my if?

4

3 回答 3

4

您可以像以前一样使用 DataType,也可以创建一个函数来执行此操作(请参阅此确定 DataColumn 是否为数字):

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.
}
于 2013-04-25T11:17:17.347 回答
1

您还可以检查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
    }

}
于 2013-04-25T11:35:42.343 回答
0

你可以试试这个:

if(Microsoft.VisualBasic.Information.IsNumeric
    (
     Activator.CreateInstance(col.DataType
    )
   )
于 2013-04-25T11:52:52.123 回答