더 나은 방법으로 DBNull을 할당하려면 어떻게 해야 합니까?
문제
값을 구문 분석해야 합니다. 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");
}
제휴하지 않습니다 StackOverflow