【问题标题】:Determine if DataColumn is numeric确定 DataColumn 是否为数字
【发布时间】:2010-12-16 02:28:33
【问题描述】:

有没有比这更好的方法来检查 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
      }
    }
  }

【问题讨论】:

    标签: c# numeric datacolumn


    【解决方案1】:

    也许你可以缩短它:

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

    【讨论】:

      【解决方案2】:

      除了将其与实际类型进行比较之外,没有其他好方法可以检查类型是否为数字。
      如果 numeric 的定义 有点不同(在您的情况下,根据代码,无符号整数不是数字),则尤其如此。

      另外,DataColumn.DataType according to MSDN 只支持以下类型:

      • 布尔值
      • 字节
      • 字符
      • 日期时间
      • 十进制
      • 双
      • Int16
      • Int32
      • Int64
      • SByte
      • 单人
      • 字符串
      • 时间跨度
      • UInt16
      • UInt32
      • UInt64
      • 字节[]

      粗体类型是数字(正如我定义的那样),因此您需要确保检查它们。

      我个人会为 DataColumn 类型(而不是 TYPE!)编写扩展方法。
      我讨厌 if...then..else 的东西,所以我使用基于 SETS 的方法,如下所示:

      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()) ....
      

      这对我来说很容易

      【讨论】:

      • 我没有包含无符号整数类型,因为它们没有在msdn.microsoft.com/en-us/library/ms131092%28SQL.90%29.aspx 中列出,但我确实喜欢你的方法。
      • @JustinStolle,我最好根据我提供的 MSDN 页面包含无符号类型。您引用的页面是特定于 SQL Server 2005 的。
      • @Dmitriy,有道理,谢谢!仅供参考,您在代码示例中的“typeof(Double)”之后缺少一个逗号。
      • 修复了这个问题。那是复制粘贴的错,不是我的:)
      • @Vincent,你不需要 ArrayList。你可以做Array.IndexOf(numericTypes, col.DataType) != -1
      【解决方案3】:

      另一种不使用数组的方法,只需一行代码:

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

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

      【讨论】:

        猜你喜欢
        • 2013-10-08
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-05
        • 2015-01-22
        • 2020-03-12
        • 1970-01-01
        相关资源
        最近更新 更多