Como posso atribuir um DBNull da melhor maneira?
Pergunta
Eu preciso analisar um valor de um DataRow
e atribuí-lo a outro DataRow
.Se a entrada for válida, preciso analisá-la para um double
, ou então adicione um DBNull
valor para a saída.Estou usando o seguinte 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;
}
Existe uma maneira melhor de fazer isso?
Solução
Que tal:
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;
}
Outras dicas
Que tal algo simples como isto:
double dbl;
if (double.TryParse(theRowInput[0] as string, out dbl))
theRowOutput[0] = dbl;
else
theRowOutput[0] = DbNull.Value;
EDITAR: Este código assume que a entrada é do tipo string.Você não estava 100% claro aí.Se fosse outro tipo, o código acima precisaria ser ligeiramente ajustado.
Aqui estão meus dois centavos confusos:
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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow