我需要从一个解析一个值 DataRow 并将其分配给另一个 DataRow.如果输入有效,那么我需要将其解析为 double, ,或者添加一个 DBNull 值到输出。我正在使用以下代码:

public double? GetVolume(object data)
{
    string colValue = data == null ? string.Empty : data.ToString();
    double volume;

    if (!Double.TryParse(colValue.ToString(), out volume))
    {
        return null;
    }
    return volume;
}

public void Assign(DataRow theRowInput,DataRow theRowOutput)
{
    double? volume = GetVolume(theRowInput[0]);

    if(volumne.HasValue)
    theRowOutput[0] = volume.value;
    else
    theRowOutput[0] = DbNull.Value;

    return theRowOutput;
}

有更好的方法吗?

有帮助吗?

解决方案

怎么样?:

    public double? GetVolume(object data)
    {
        double value;
        if (data != null && double.TryParse(data.ToString(), out value))
            return value;
        return null;
    }

    public void Assign(DataRow theRowInput, DataRow theRowOutput)
    {
        theRowOutput[0] = (object)GetVolume(theRowInput[0]) ?? DBNull.Value;
    }

其他提示

像这样简单的东西怎么样:

double dbl;
if (double.TryParse(theRowInput[0] as string, out dbl))
    theRowOutput[0] = dbl;
else
    theRowOutput[0] = DbNull.Value;

编辑: 此代码假定输入为string类型。你不是100%清楚。如果它是另一种类型,上面的代码需要稍微调整。

这是我的两分钱:

decimal dParse;
if ((cells[13] == "" ? LP_Eur = DBNull.Value : (Decimal.TryParse(cells[13], NumberStyles.Number, NumberFormat, out dParse) ? LP_Eur = dParse : LP_Eur = null)) != null) {
    throw new Exception("Ivalid format");
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top