Reputation: 2060
I'm importing data from a database into a table with the following code:
public double[,] toValueArray(string fieldPrefix, int firstIndex, int lastIndex)
{
// return a bunch of value columns as a double array
double[,] outArr = new double[TableRowCount,lastIndex-firstIndex+1];
for (int i = firstIndex; i <= lastIndex; i++)
{
var col = TheDataTable.Columns[fieldPrefix + i];
int r = -1;
foreach (DataRow row in TheDataTable.Rows)
{
outArr[++r, i - firstIndex] = (row[col] == null || row[col] == DBNull.Value) ? 0 : (double)row[col];
}
}
return outArr;
}
The problem is, sometimes the database may be storing these as a decimal, and sometimes a double. How can I convert use .toDouble()
only if the type is a decimal?
Upvotes: 1
Views: 43
Reputation: 38608
First, use 0D
to have a double value and avoit implicit conversion of int
to double
. The conversion you can try doing it using the ToDouble
static method from Convert
type. For sample:
double setValue = 0D;
if (row[col] != null && row[col] != DBNull.Value)))
setValue = (row[col] is decimal) ? Convert.ToDouble(row[col]) : (double) row[col];
outArr[++r, i - firstIndex] = setValue;
Upvotes: 1