代码之家  ›  专栏  ›  技术社区  ›  JustinStolle

确定DataColumn是否为数字

  •  15
  • JustinStolle  · 技术社区  · 15 年前

    有没有比这更好的方法来检查DataTable中的DataColumn是否为数字(来自SQL Server数据库)?

      Database db = DatabaseFactory.CreateDatabase();
      DbCommand cmd = db.GetStoredProcCommand("Get_Some_Data");
      DataSet ds = db.ExecuteDataSet(cmd);
    
      foreach (DataTable tbl in ds.Tables) {
        foreach (DataColumn col in tbl.Columns) {
          if (col.DataType == typeof(System.Single)
            || col.DataType == typeof(System.Double)
            || col.DataType == typeof(System.Decimal)
            || col.DataType == typeof(System.Byte)
            || col.DataType == typeof(System.Int16)
            || col.DataType == typeof(System.Int32)
            || col.DataType == typeof(System.Int64)) {
            // this column is numeric
          } else {
            // this column is not numeric
          }
        }
      }
    
    3 回复  |  直到 15 年前
        1
  •  40
  •   Dmytrii Nagirniak    15 年前

    除了将该类型与实际类型进行比较外,没有什么好方法可以检查该类型是否为数字类型。
    如果 数字的定义 有点不同(在您的例子中,根据代码,-无符号整数不是数字)。

    另一件事是 DataColumn.DataType according to MSDN 仅支持以下类型:

    • 布尔值
    • 烧焦
    • 日期时间
    • 双重的
    • Int16
    • Int32
    • 斯拜特
    • 单身
    • 一串
    • UInt16
    • UInt32
    • UInt64

    这个 大胆的

    我个人会为DataColumn类型编写一个扩展方法(不是为该类型!)。
    如果…那么…否则 设置 -基于此的方法,如下所示:

    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);
    }
    

    其用法是:

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

    这对我来说很容易

        2
  •  2
  •   S.Serpooshan    11 年前

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

    这行代码既可以用作普通助手方法,也可以用作扩展方法。

        3
  •  1
  •   Jonathan    15 年前

    也许您可以通过以下方式将其缩短:

    System.Type theType = col.DataType AS System.Type
    if(theType  == System.Single || theType  == System.Double...) {}