Datatable to Multidimensional Array
Asked Answered
N

3

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

Nic answered 19/1, 2012 at 20:35 Comment(2)
There is a good reason for looping, see #8918657Arie
don't you think you will loop over all the records during conversion?Granulose
H
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();
Hereditable answered 19/1, 2012 at 20:43 Comment(4)
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.Nic
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.Hereditable
@Nic I am getting the same error, even with this split up over multiple lines. Did you ever get it resolved?Tarter
@Tarter yep, try something like this var foo = dt.AsEnumerable().Select(x => x.ItemArray).ToArray();Nic
A
4

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

Acreinch answered 30/10, 2013 at 10:29 Comment(0)
F
0

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

Flourishing answered 20/1, 2012 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.