Lukas
Lukas

Reputation: 2923

Convert DataTable into object[ , ] array with LINQ

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.

Upvotes: 0

Views: 3222

Answers (1)

D Stanley
D Stanley

Reputation: 152511

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
   }
}

Upvotes: 3

Related Questions