chiro3110
chiro3110

Reputation: 77

Array of 2-D array C#?

Can we define an array of 2D array in C# of this manner? Or any alternate approach to obtain similar dataset?

double[][,] testArray = new double[a][b,c];

Note: All the three indices - a,b and c are obtained in runtime.

Thanks

Upvotes: 1

Views: 224

Answers (2)

trashr0x
trashr0x

Reputation: 6575

Sure.

int[][,] arrayOf2DArrays = 
{
    new int[,] {{1, 2, 3}, {4, 5, 6}},
    new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}},
    new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13, 14, 15}}
};

This is essentially a one-dimensional jagged array that contains three two-dimensional arrays, each of different size.

The elements can be accessed in the following manner:

var element = arrayOf2DArrays[0][0, 0]; // etc
Console.WriteLine(element);

..and arrayOf2DArrays.Length will, in the example above, return 3, as arrayOf2DArrays contains three two-dimensional arrays.

Jagged Arrays (C# Programming Guide) - MSDN

Upvotes: 4

Jakub Dąbek
Jakub Dąbek

Reputation: 1044

You can do it, but you have to initialize each 2D array separately :

double[][,] testArray = new double[a][,];
for(int i = 0; i < a; i++)
{
    testArray[i] = new double[b, c];
}

Another way is to just declare a 3D array:

double[,,] testArray3D = new double[a, b, c];

That is, you can make that change if every 2D array you wanted in the beginning is to have the same dimensions

Upvotes: 8

Related Questions