I'm working on a multidimensional array in C# and I was wondering whether I can fill two dimensions of a 3 dimensional array using another 2d array. I have two arrays:
byte[,,] thArray = new byte[1000, 1000, 1000];
byte[,] twArray = new byte[1000, 1000];
Now I need to do something like this:
thArray[,,0] = twArray;
CodePudding user response:
Filling any kind of array requires copying. So the trivial answer would be to write a double loop copying each value from twArray
to the thArray
. Other answers show how to do this already.
However, I might share some experiences using large multidimensional arrays.
For 2D arrays I prefer using a wrapper around a 1D array rather then the built in multidimensional array. This makes some operations faster, and allows for things like using Buffer.BlockCopy for copying large sections, and is usually easier to use when inter operating with other systems. Indexing a value can be done like y*width x
.
Using a custom type also removes the risk of calling .GetLength()
in a loop check, since this method is several times slower than checking a regular property. An easy mistake to make, but one that can make loops much slower.
For 3D arrays you could use the same approach, and just add another dimension. But in my experience this tend to be slower than using a jagged array. So I would recommend using something like a byte[][] myArray
for a 3D array and index it using myArray[z][y * width x]
, preferably with some custom class that can do all this indexing.
CodePudding user response:
You can use 2 for loops to copy the values of the 2-dimensional array to the 3-dimensional array, but leave the 3-dimensional arrays z-value 0:
int height = twArray.GetLength(0);
int width = twArray.GetLength(1);
for (int i = 0; i < height; i )
{
for (int j = 0; j < width; j )
{
thArray[i, j, 0] = twArray[i, j];
}
}
CodePudding user response:
Yes, you can do it in a good old for
loop:
for (int x = 0; x < thArray.GetLength(0); x)
for (int y = 0; y < thArray.GetLength(1); y)
thArray[x, y, 0] = twArray[x, y];
If you wan to assign in one go you can use byte[][,] thArray
- array of 2D arrays:
byte[][,] thArray = new byte[1000][,];
thArray[0] = twArray;