0

I sincerely apologize if this has been asked before; maybe I am just blind and not finding it. Is it possible to convert a DataTable into an object[ , ] type array using LINQ? Using the following code I can convert it into object[][] but that's not what I need unfortunately:

object[][] tableEnumerable = dtReportData.AsEnumerable().Select(x => x.ItemArray).ToArray();

What I need is:

object [,] = ....?

Thank you in advance for any help and again, I apologize if this is a duplicate post.

EDIT: I do not want object[][] as the posted solution is referring to, I need object[,]. At least learn to read people before you start subtracting points.

Lukas
  • 2,885
  • 2
  • 29
  • 31
  • possible duplicate of [Datatable to Multidimensional Array](http://stackoverflow.com/questions/8932900/datatable-to-multidimensional-array) – Dylan Corriveau Jun 17 '15 at 16:43
  • Right, I actually looked at that but that will net me object[][] instead of object[,] Thank you for the suggestion however. – Lukas Jun 17 '15 at 16:44
  • Linq cannot create a rectangular array - you'll need to use nested `for` loops. – D Stanley Jun 17 '15 at 16:55
  • Thank you Stanley. I opted for LINQ due to one-line code and hopefully a faster conversion time, but if it can't be done, then perhaps it's no wonder that I could not find such an answer. – Lukas Jun 17 '15 at 17:04
  • 1
    Linq is just a shorter _syntax_ for normal loops - you usually don't see any performance benefit. In fact, there's usually a _very slight_ performance hit due to the overhead it has. – D Stanley Jun 17 '15 at 17:09

1 Answers1

3

You cannot use Linq to create a rectangular array - Linq only operates on single-dimension arrays. You will need to use traditional for loops:

object[,] objectArray = new object[dtReportData.Rows.Count,
                                   dataTable1.Columns.Count];

for(int row = 0; row < dtReportData.Rows.Count; row++)
{
  for(int col = 0; col < dtReportData.Columns.Count; col++)
  {
    objectArray[row, col] = dtReportData.Rows[row][col];
  }
}

You could make this an extension method of DataTable to make the syntax cleaner if you like:

object[][] tableEnumerable = dtReportData.ToRectangularArray()

The extension method would be something like:

public static class MyDataTableExtensions
{
   public static object[,] ToRectangularArray(this DataTable dt)
   {
       // code above goes here
   }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • So it can't be done with LINQ alone, fair enough. I'll mark this as an answer since there is a work around provided. Thank you! – Lukas Jun 17 '15 at 18:42