How can I assign DBNull better?

I need to parse a value from a DataRow and assign it to another DataRow . If the input is valid, then I need to DBNull it to double or add a DBNull value to the output. I am using the following 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; } 

Is there a better way to do this?

+4
source share
4 answers

What about:

  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; } 
+10
source

How about something simple:

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

EDIT: This code assumes the input file has a type string. There you were not 100% understood. If it was a different type, you would need to slightly modify the code above.

0
source
 public void Assign(DataRow theRowInput,DataRow theRowOutput) { //If value is null then assign DB.Null else leave it as it is if (theRowInput[0]==null) theRowOutput[0]= DbNull.Value; else theRowOutput[0]=theRowinput[0]; return theRowOutput; } 
0
source

Here are my two dirty cents:

 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"); } 
0
source

Source: https://habr.com/ru/post/1340131/


All Articles