有没有比这更好的方法来检查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
}
}
}发布于 2009-11-13 07:04:58
除了将其与实际类型进行比较之外,没有好的方法来检查类型是否为数字类型。
如果数字的定义有点不同,这一点尤其正确(在您的例子中,根据代码,-无符号整数不是数字)。
另一件事是DataColumn.DataType according to MSDN只支持以下类型:
粗体的类型是数字(根据我的定义),所以您需要确保检查它们。
我个人会为DataColumn类型编写一个扩展方法(而不是为该类型!)。
我讨厌if...then..else,所以我使用基于集合的方法,如下所示:
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()) ....这对我来说很简单
发布于 2013-09-23 18:53:50
另一种不使用数组的方法,只需一行代码:
return col != null && "Byte,Decimal,Double,Int16,Int32,Int64,SByte,Single,UInt16,UInt32,UInt64,".Contains(col.DataType.Name + ",");这行代码既可以用作普通的帮助器方法,也可以用作扩展方法。
发布于 2009-11-13 06:51:31
也许你可以让它变得更短:
System.Type theType = col.DataType AS System.Type
if(theType == System.Single || theType == System.Double...) {}https://stackoverflow.com/questions/1725903
复制相似问题