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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With