确定DataColumn是否为数字
有没有比这更好的方法来检查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 } } }
除了将其与实际类型进行比较之外,没有好的方法来检查类型是否为数字。
如果numeric的定义有点不同(在您的情况下,根据代码, – 无符号整数不是数字),尤其如此。
另一件事是, 根据MSDN的DataColumn.DataType仅支持以下类型:
- 布尔
- 字节
- 烧焦
- 约会时间
- 十进制
- 双
- INT16
- INT32
- Int64的
- 为SByte
- 单
- 串
- 时间跨度
- UINT16
- UInt32的
- 答:64
- 字节[]
粗体类型是数字(我定义它)所以你需要确保你检查它们。
我个人会为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()) ....
这对我来说很容易
不使用数组的另一种方法,只需一行代码:
return col != null && "Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(col.DataType.Name + ",");
这行代码既可以用作普通的辅助方法,也可以用作扩展方法。
也许你可以缩短它:
System.Type theType = col.DataType AS System.Type if(theType == System.Single || theType == System.Double...) {}