简体   繁体   中英

C# - Dealing with database type may be decimal or double

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM