Is there a better way than this to check if a DataColumn in a DataTable is numeric (coming from a SQL Server database)?
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
}
}
}
Another method without using Arrays, just by one line of code:
This line of code can be used either as a normal helper method or as an extension method.
Maybe you could make it shorter with:
There is no good way to check if the type is numeric except comparing it to the actual types.
This is especially true if the definition of numeric is a bit different (in your case, according to code, - unsigned integers are not numerics).
Another thing is that DataColumn.DataType according to MSDN only supports following types:
The bolded types are numerics (as I define it) so you need to make sure you check them.
I personally would write an extension method for the DataColumn type (not for the TYPE!).
I hate the if...then..else thing so instead I use a SETS-based approach, like this:
And the usage would be:
which is easy enough for me