Frage

Ich muss einen Wert aus a analysieren DataRow und weisen Sie es einem anderen zu DataRow.Wenn die Eingabe gültig ist, muss ich sie in a analysieren double, oder fügen Sie a hinzu DBNull Wert an die Ausgabe.Ich verwende den folgenden Code:

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

Gibt es einen besseren Weg, es zu tun?

War es hilfreich?

Lösung

Wie wäre es mit:

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

Andere Tipps

Wie wäre es mit so etwas Einfachem:

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

BEARBEITEN: Dieser Code geht davon aus, dass die Eingabe vom Typ „String“ ist.Da warst du nicht 100%ig klar.Wenn es sich um einen anderen Typ handelte, müsste der obige Code leicht angepasst werden.

Hier sind meine zwei unordentlichen Cent:

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");
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top