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.

5
  • possible duplicate of Datatable to Multidimensional Array Commented Jun 17, 2015 at 16:43
  • Right, I actually looked at that but that will net me object[][] instead of object[,] Thank you for the suggestion however. Commented Jun 17, 2015 at 16:44
  • Linq cannot create a rectangular array - you'll need to use nested for loops. Commented Jun 17, 2015 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. Commented Jun 17, 2015 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. Commented Jun 17, 2015 at 17:09

1 Answer 1

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
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.