Initializing jagged arrays

Viewed 23481

I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,]).

I can write code:

int[][][] count = new int[10][][];

for (int i = 0; i < 10; i++) 
{
    count[i] = new int[10][];

    for (int j = 0; j < 10; j++)
        count[i][j] = new int[10];
}

but I am looking for a more beautiful way for it. May be something like that:

int[][][] count = new int[10][10][10];
9 Answers

With a little help from Linq

int[][][] count = new int[10][][].Select(t => new int[10][].Select(tt => new int[10]).ToArray()).ToArray();

It sure isn't pretty and probably not fast but it's a one-liner.

Why don't you try this?

int[,,] count = new int[10, 10, 10]; // Multi-dimentional array.

Any problem you see with this kind of representation??

Related