Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# assign 1 dimensional array to 2 dimensional array syntax

I want to do something like:

object[] rowOfObjects = GetRow();//filled somewhere else
object[,] tableOfObjects = new object[10,10];

tableOfObjects[0] = rowOfObjects;

is this somehow possible and what is the syntax?

or I need to do this:

for (int i = 0; i < rowOfObjects.Length; i++)
{
   tableOfObjects[0,i] = rowOfObjects[i];
}

and fill up the 2 dimensional arrays row using a loop?

Thanks

like image 450
m3ntat Avatar asked Jul 08 '09 16:07

m3ntat


2 Answers

No, if you are using a two dimensional array it's not possible. You have to copy each item.

If you use a jagged array, it works just fine:

// create array of arrays
object[][] tableOfObject = new object[10][];
// create arrays to put in the array of arrays
for (int i = 0; i < 10; i++) tableOfObject[i] = new object[10];

// get row as array
object[] rowOfObject = GetRow();
// put array in array of arrays
tableOfObjects[0] = rowOfObjects;

If you are getting all the data as rows, you of course don't need the loop that puts arrays in the array of arrays, as you would just replace them anyway.

like image 138
Guffa Avatar answered Oct 17 '22 12:10

Guffa


If your array is an array of value types, it is possible.

int[,] twoD = new int[2, 2] {
    {0,1},
    {2,3}
};
int[] oneD = new int[2] 
    { 4, 5 };
int destRow = 1;
Buffer.BlockCopy(
    oneD, // src
    0, // srcOffset
    twoD, // dst
    destRow * twoD.GetLength(1) * sizeof(int), // dstOffset
    oneD.Length * sizeof(int)); // count
// twoD now equals
// {0,1},
// {4,5}

It is not possible with an array of objects.

Note: Since .net3.5 this will only work with an array of primitives.

like image 11
Matthew Finlay Avatar answered Oct 17 '22 10:10

Matthew Finlay