¿Cómo puedo asignar un DBNull de mejor manera?
Pregunta
Necesito analizar un valor de un DataRow
y asignarlo a otro DataRow
.Si la entrada es válida, entonces necesito analizarla en un double
, o bien añadir un DBNull
valor a la salida.Estoy usando el siguiente código:
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;
}
Hay una mejor manera de hacerlo?
Solución
Qué tal si:
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;
}
Otros consejos
¿Qué tal algo tan simple como esto?
double dbl;
if (double.TryParse(theRowInput[0] as string, out dbl))
theRowOutput[0] = dbl;
else
theRowOutput[0] = DbNull.Value;
EDITAR: Este código supone que la entrada es de tipo cadena.No estabas 100% claro ahí.Si fuera de otro tipo, sería necesario modificar ligeramente el código anterior.
Aquí están mis dos centavos desordenados:
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");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow