سؤال

أحتاج إلى تحليل قيمة من أ 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;

تحرير: يفترض هذا الرمز أن الإدخال من نوع السلسلة.لم تكن واضحا 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