7

Is there an easy way to convert a Datatable to a multidimensional string array?

Maybe using LINQ?

There's gotta be a better way than manually looping through all the columns/rows...

Greg
  • 8,574
  • 21
  • 67
  • 109

3 Answers3

8

Linq is the answer. You can convert a DataTable to IEnumerable using the AsEnumerable method. Then, the ToArray() converts it to an array.

var tableEnumerable = DataTableName.AsEnumerable();
tableArray = tableEnumerable.ToArray();
Gabriel GM
  • 6,391
  • 2
  • 31
  • 34
  • 2
    sorry, I've never used LINQ before. I'm getting this error `Cannot implicitly convert type 'System.Data.DataRow[]' to 'string[*,*]'` Any help would be greatly appreciated. – Greg Jan 19 '12 at 21:46
  • are you getting that error on the line I gave you? If so, can you break it into different parts (enumerable = DataTable.asenumerable(); tablearray = enumerable.toarray();) and see if it still react the same. – Gabriel GM Jan 20 '12 at 12:35
  • @Greg I am getting the same error, even with this split up over multiple lines. Did you ever get it resolved? – Rachel Apr 03 '13 at 19:52
  • 1
    @Rachel yep, try something like this `var foo = dt.AsEnumerable().Select(x => x.ItemArray).ToArray();` – Greg Apr 03 '13 at 21:03
4

yourTable.AsEnumerable().Select(row => row.ItemArray).ToArray()

0

try dt.Rows.Cast().Select(//datarow to strings)

Gavin Fang
  • 367
  • 5
  • 7