yogi
yogi

Reputation: 19619

Convert a DataTable to multidimensional array C#

I'm trying to convert a DataTable's rows into multidimensional array:

DataTable DT = new DataTable();
DT.Columns.AddRange
(
   new DataColumn[]
   { 
           new DataColumn("LA_ID"), 
           new DataColumn("contractid") 
   }
);

for(int i=1000; i<=1100; i++)
   DT.Rows.Add(i, i);

EnumerableRowCollection<DataRow> appsEnum = DT.AsEnumerable();

int[,] apps = appsEnum.
               Where(x => x.Field<int>("LA_ID") > 1050).
               Select(x => x.Field<int>("LA_ID"), x.Field<int>("contractid")).
--Error Here-------------------------------------^
               ToArray();

Can anyone help plz.

enter image description here

Upvotes: 0

Views: 3347

Answers (2)

ASh
ASh

Reputation: 35720

the best you can get with ToArray() method is jagged array

int [][] apps = appsEnum.
           Where(x => x.Field<int>("laid") > 1050).
           Select(x => new int[] {x.Field<int>("LA_ID"), x.Field<int>("contractid")}).
           ToArray();

consider another approach

DataRow[] rows = DT.Select("laid > 1050");

int[,] apps = new int[rows.Length, 2];

for(int r=0; r<rows.Length; r++)
{
   apps[r,0] = rows[r].Field<int>("LA_ID");
   apps[r,1] = rows[r].Field<int>("contractid");
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273784

There is no version of .ToArray() that supports more than 1 dimension. You will need a for-loop here.

It could probably work with a int[][] but not for int[,]

Upvotes: 2

Related Questions