更改 DataTable 中字符串等于数字的列

Change a column in a DataTable where string equal a number

在 DataTable 中,我有一个字符串列 Salenumber。 我想删除介于 1 - 100 之间的数字并将其设置为“”。

我不能像这样使用 IF 语句,但这是我想要做的。

if (row["Salenumber"].ToString() >= 1 && row["Salenumber"].ToString() <= 100) 
    row.SetField("Salenumber", "");

我无法将列更改为 int。也许如果有办法将其更改为 int remove 1 - 100 然后将其更改回来。

有什么好的方法吗?

您无需将列更改为 int,只需将单元格值转换为 int 即可在 if 语句中使用

if (int.Parse(row["Salenumber"].ToString()) >= 1 && int.Parse(row["Salenumber"].ToString()) <= 100) 
       row.SetField("Salenumber", "");

试试这个:

double RowDoubleValue;
foreach(DataRow row in YourDataTable) 
{
    if(Double.TryParse(row["Salenumber"].ToString(), out RowDoubleValue) && RowDoubleValue >= 1.0 && RowDoubleValue <= 100.0) 
    {
      row["Salenumber"] = "";
    }
}

另一种选择是将条件封装到方法中,如评论中建议的Boas Enkler

foreach(DataRow row in YourDataTable) 
{
    if(IsANumberWithinRange(row["Salenumber"].ToString(), 1.0, 100.0)) 
    {
      row["Salenumber"] = "";
    }
}

private bool IsANumberWithinRange(string InputString, double MinValue, double MaxValue) 
{
    double Value;
    return (Double.TryParse(InputString, out RowIntValue) && RowIntValue >= MinValue && RowIntValue <= MaxValue)
}

注意:我已从 int 更改为 double,因为这是一个字符串列,它可能包含任何类型的数字。