0

I'm using the Math.Net Numerics package to do some statistics work with regression, etc. Because an assortment of different columns from a particular table may be used as independent variables, I decided to write a method that will create a Matrix from a DataTable directly from a query by creating a double[][] array and passing it to the DenseOfRowArrays() method in MathNet.Numerics. The calling code will ensure that only columns with numeric values will be present in the DataTable.

I got this far following the answers here: C# Cast Entire Array?

public static Matrix<double> DenseOfDataTable(DataTable dt)
        {
            double[][] arrayFromDataTable = dt.AsEnumerable().Select(row => Array.ConvertAll(row.ItemArray, item => (double)item)).ToArray();

            return CreateMatrix.DenseOfRowArrays(arrayFromDataTable);
        }

My problem is when running it I get an InvalidCastException on (double)item with item showing a value of 0.000 when inspected.

Community
  • 1
  • 1
Valuator
  • 3,262
  • 2
  • 29
  • 53
  • 1
    Try changing it for `Convert.ToDouble()` – I.B Apr 20 '17 at 17:22
  • That's all it needed, silly mistake from me starting out writing it as a generic. – Valuator Apr 20 '17 at 17:43
  • Possible duplicate of [How to cast from various unknown numeric types to double](http://stackoverflow.com/questions/43501237/how-to-cast-from-various-unknown-numeric-types-to-double) – I.B Apr 20 '17 at 17:47
  • @CNuts I have an off topic question. You have answered this question with a comment. Why you don't create an answer and let it mark as accepted? Why I'm asked it? The question is not official answered and other SO user think that there is no solution for this problem. I'm new, so I try to understand it. – Sean Stayns Apr 20 '17 at 17:54
  • 2
    @SeanStayn It's okay. My point of view is that I already answered pretty much the same question in the duplicate I flagged so I would rather have this one closed as duplicate than repeat myself. And I'm pretty sure there's even more similar answers out there. – I.B Apr 20 '17 at 17:59

0 Answers0