Determine if DataColumn is numeric

前端 未结 3 799
小鲜肉
小鲜肉 2020-12-09 10:47

Is there a better way than this to check if a DataColumn in a DataTable is numeric (coming from a SQL Server database)?

  Database db = DatabaseFactory.Creat         


        
相关标签:
3条回答
  • 2020-12-09 11:14

    There is no good way to check if the type is numeric except comparing it to the actual types.
    This is especially true if the definition of numeric is a bit different (in your case, according to code, - unsigned integers are not numerics).

    Another thing is that DataColumn.DataType according to MSDN only supports following types:

    • Boolean
    • Byte
    • Char
    • DateTime
    • Decimal
    • Double
    • Int16
    • Int32
    • Int64
    • SByte
    • Single
    • String
    • TimeSpan
    • UInt16
    • UInt32
    • UInt64
    • Byte[]

    The bolded types are numerics (as I define it) so you need to make sure you check them.

    I personally would write an extension method for the DataColumn type (not for the TYPE!).
    I hate the if...then..else thing so instead I use a SETS-based approach, like this:

    public static bool IsNumeric(this DataColumn col) {
      if (col == null)
        return false;
      // Make this const
      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 the usage would be:

    if (col.IsNumeric()) ....
    

    which is easy enough for me

    0 讨论(0)
  • 2020-12-09 11:18

    Another method without using Arrays, just by one line of code:

    return col != null && "Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(col.DataType.Name + ",");
    

    This line of code can be used either as a normal helper method or as an extension method.

    0 讨论(0)
  • 2020-12-09 11:25

    Maybe you could make it shorter with:

    System.Type theType = col.DataType AS System.Type
    if(theType  == System.Single || theType  == System.Double...) {}
    
    0 讨论(0)
提交回复
热议问题