gpt4 book ai didi

c# - 确定 DataColumn 是否为数字

转载 作者:可可西里 更新时间:2023-11-01 03:04:27 26 4
gpt4 key购买 nike

有没有比这更好的方法来检查 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 的定义 有点不同(在您的情况下,根据代码,无符号整数不是数字),则尤其如此。

另一件事是DataColumn.DataType according to MSDN仅支持以下类型:

  • bool 值
  • 字节
  • 字符
  • 日期时间
  • 十进制
  • 双人间
  • Int16
  • Int32
  • Int64
  • 字节
  • 单例
  • 字符串
  • 时间跨度
  • UInt16
  • UInt32
  • UInt64
  • 字节[]

粗体 类型是数字(按照我的定义),因此您需要确保检查它们。

我个人会为 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()) ....

这对我来说很简单

关于c# - 确定 DataColumn 是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1725903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com