2009-11-12 52 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 + ","); 

這行代碼可以用作普通的輔助方法或擴展方法。