Alfredo
Alfredo

Reputation: 81

Add a dimension to a multidimensional array in c#

I have a multidimensional array

byte[,] matrix;

and i want copy in a 3 dimension array

byte[,,] 3dplan; 

in this way

3dplan[,,0]=matrix

What is the fastest way to accomplish this task in c#?

Upvotes: 8

Views: 1829

Answers (2)

Mike Tsayper
Mike Tsayper

Reputation: 1802

You can copy 2d array into 3d array with Buffer.BlockCopy:

var _3dplan = new int[2, 2, 2];
var _2dplan = new int[2, 2] { { 1, 1 }, { 1, 1 } };
var index = 0;
var size = _2dplan.Length * sizeof(int);
Buffer.BlockCopy(_2dplan, 0, _3dplan, index * size, size);

Upvotes: 0

SLaks
SLaks

Reputation: 887225

You need to manually copy the elements in a nested loop; there is no faster way.

If you switch to a jagged array (byte[,][] or byte[][][]), you can insert the smaller array as-is into a slot in the larger array (although they will both refer to the same array instance and will pick up changes)

Upvotes: 6

Related Questions