Search code examples
c#.netdataset

C# Create double[][] from DataTable


I have a DataTable where every entry in every row and column is a double. I need to convert it to a two dimensional double[][] object. There are no column headers and the number of rows and columns can be different each time.

Is there Linq to simplify this? Can I apply Math.Round() for each value as I build my double[][] object?


Solution

  • Having DataTable with all columns that can be converted into double (i.e. columns can be of type float, int etc.) you can put something like this:

    using System.Linq;
    
    ...
    
    DataTable table = ...
    
    double[][] array = table
      .Rows
      .OfType<DataRow>()
      .Select(dataRow => dataRow
        .ItemArray
        .Select(item => Convert.ToDouble(item))
        .ToArray())
      .ToArray();
    

    Sure, you can add some processing, say, Math.Round if required; add it after the inner Select:

       ...
       .Select(item => Convert.ToDouble(item)) // from now on we have double
       .Select(value => Math.Round(value, 2))  // Let's round the values
       .ToArray())
       ...