2009-11-12 53 views
13

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

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

回答

36

还有就是要检查类型是除了它比较实际类型的数字没有什么好办法。
如果数字的定义有点不同(在您的情况下,根据代码, - 无符号整数不是数字),这尤其如此。

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

  • 布尔
  • 字节
  • 字符
  • 日期时间
  • 十进制
  • 的Int16
  • 的Int32
  • 的Int64
  • 为SByte
  • 字符串
  • 时间跨度
  • UINT16
  • UInt32的
  • UINT64
  • 字节]

加粗类型NUMERICS(我定义它),所以你需要确保你检查他们。

我个人会为DataColumn类型(不适用于TYPE!)编写扩展方法。
我讨厌if ... then ..否则的事情,所以我代替使用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()) .... 

这是很容易够我

+2

+1用于扩展方法,让痛苦保持1位 – 2009-11-12 23:10:14

+0

我没有包含无符号整数类型,因为它们没有在http://msdn.microsoft.com/en-us/library/ms131092%28SQL中列出.90%29.aspx但我喜欢你的方法。 – JustinStolle 2009-11-12 23:11:07

+0

@JustinStolle,根据我提供的MSDN页面,我最好包含未签名的类型。您引用的页面是特定于SQL Server 2005的页面。 – 2009-11-12 23:14:07

1

也许你可以把它缩短了与:

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

另一种方法无需使用阵列,只需一行代码:

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

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