Jus*_*lle 16 c# numeric 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dmy*_*iak 39
除了将其与实际类型进行比较之外,没有好的方法来检查类型是否为数字.
如果numeric的定义有点不同(在您的情况下,根据代码, - 无符号整数不是数字),尤其如此.
另一件事是,根据MSDN的DataColumn.DataType仅支持以下类型:
该加粗类型NUMERICS(我定义它),所以你需要确保你检查.
我个人会为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);
}
Run Code Online (Sandbox Code Playgroud)
用法是:
if (col.IsNumeric()) ....
Run Code Online (Sandbox Code Playgroud)
这对我来说很容易