gpt4 book ai didi

c# - 如何检查列是否可以转换为 double ? (DataTable.Column.DataType)

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:42 24 4
gpt4 key购买 nike

我需要一个简单的条件来替换这个(不完整的)if 条件。

// i dont want to write all possible data types
if (col.DataType == typeof(int) || col.DataType == typeof(int64) ... all types)
{
// i want to do something on numeric columns
// (convert all numbers to double datatype)
}
else
{
// string and other non-numbers will remain unchanged
}

我正在尝试这样的事情:

col.DataType.IsNumeric()

但是那个类中没有这个方法。

我不能对数据使用 TryParse() 方法,因为数据太多了。

条件只能由 DataTable 列数据类型属性确定。

有什么简单的方法可以简化我的if吗?

最佳答案

您可以像以前一样使用 DataType,或者创建一个函数来执行此操作(请参阅 Determine if DataColumn is numeric):

public static bool IsNumeric(this DataColumn col) {

if (col == null)
return false;

// all numeric types
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()) 
{
// the column is numeric
}

现在,对于您专栏的内容,您可以尝试使用 double.TryParse() 方法,如下所示:

double temp;
if (double.TryParse(col["Column"].ToString(), out temp))
{
// the content can be converter and you can read it from temp variable.
}

关于c# - 如何检查列是否可以转换为 double ? (DataTable.Column.DataType),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16213265/

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