简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM