Convert from List to 3D Array C#

Hey Guys,

I need to be able to re convert the 3D Array output of a C# scripting component (which seems to "flatten"it out by defualt ) back to its original form as input for another process. I will be in control of the dimensions and the Array dimensions will always be in the order of

      for (int i = 0; i < x; i++)
                {
                    for (int j = 0; j < y; j++)
                    {
                        for (int k = 0; k < z; k++)
                        {
                             // bla bla
                        }

                    }
                }

I have converted a Array/List to a 2D Array before using

T[,] output = new T[height, width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                output[i, j] = input[i * width + j];
            }
        }

I just cannot seem to wrap my head around the index formula for the 3D Array!..

Any help would be appreciated

Hi @rawitscher-torres,

If you have this:

var array3D = new[, ,] { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } };

and you do this:

var xCount = array3D.GetLength(0);
var yCount = array3D.GetLength(1);
var zCount = array3D.GetLength(2);
var list = new List<int>();
for (var x = 0; x < xCount; x++)
  for (var y = 0; y < yCount; y++)
    for (var z = 0; z < zCount; z++)
      list.Add(array3D[x, y, z]);

You can get back there doing this:

var test3d = new int[xCount, yCount, zCount];
var index = 0;
for (var x = 0; x < xCount; x++)
  for (var y = 0; y < yCount; y++)
    for (var z = 0; z < zCount; z++)
      test3d[x, y, z] = list[index++];

– Dale

there are also jagged arrays -> array[][][]. faster and allowing to be irregular in size, but a bit more cumberstrone to work with.

Hi Dale,

I am pretty sure I tried something very similar before! but anyhow its a much more elegant solution.