【问题标题】:How can I assign a DBNull in a better way?如何以更好的方式分配 DBNull?
【发布时间】:2011-02-17 07:07:19
【问题描述】:

我需要从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;
}

有没有更好的方法?

【问题讨论】:

    标签: c# .net parsing datarow dbnull


    【解决方案1】:

    怎么样:

        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;
        }
    

    【讨论】:

    • @Adeel 我们通过索引器分配给DataRow 单元格,这固有地 涉及装箱...
    【解决方案2】:

    像这样简单的事情怎么样:

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

    编辑: 此代码假定输入是字符串类型。你在那里不是100%清楚。如果是其他类型,上面的代码需要稍微调整一下。

    【讨论】:

    • as string 并不完全相同 - 例如,原始单元格可能是 int。实际上,Convert.ToDouble 总体上可能是更好的选择...
    • @Marc 你从哪里得到的原始单元格可能是int
    • 纯看代码,除了object....以外对源码一无所知。
    • @Marc 他正在从数据库中读取它。我以为他知道那种类型。我猜他没有明确表达。
    【解决方案3】:

    这是我的两个凌乱的美分:

    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");
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      相关资源
      最近更新 更多