Kamil
Kamil

Reputation: 13931

How to check if column can be converted to double? (DataTable.Column.DataType)

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?

Upvotes: 1

Views: 2921

Answers (3)

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

You may try this:

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

Upvotes: 0

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

You can also check DataColumn.DataType.Name property. like :

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
    }

}

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38598

You could use the DataType as you did, or make a function to do this (see this 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);
}

And use

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

Now, for the content of your column, you could try using double.TryParse() method, something like this:

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

Upvotes: 4

Related Questions