简体   繁体   中英

Jagged array with two 2d array

How to create a jagged array that consists of two 2d array? please help. Thank you.

int[][] jaggedArray = new int[3][];

the above code creates a single-dimensional array that has three elements, each of which is a single-dimensional array of integers. Can any one help me in creating a two 2d array.

What about this:

int[][,] jaggedArray = new int[3][,];

The , creates the 2D array in the jagged array. Read more on Multi-dimensional arrays on MSDN .

Next, you have to initialize every 2D array inside that array:

int[,] 2dArray1 = new int[2,3];
jaggedArray[0] = 2dArray1;

int[,] 2dArray2 = new int[4,5];
jaggedArray[1] = 2dArray2;

And so on.

I think you want something like this,

var jaggedArray = new[]
        {
            new[] { 1 },
            new[] { 1, 2 ,3 },
            new[] { 1, 2 }
        };

this creates a "jagged" array, with two dimensions where each "row" has a different length.

All of the following assertions would be True .

jaggedArray.Length == 3
jaggedArray[0].Length == 1
jaggedArray[1].Length == 3
jaggedArray[2].Length == 2

If you knew the lengths were fixed but, didn't know the data, you could do,

var jaggedArray = new[] { new int[1], new int[3], new int[2] };

Following on from you comment, maybe you want something like this,

var jaggedArray1 = new[]
        {
            new[] { 1, 2, 3, 4 },
            new[] { 1, 2, 3 },
            new[] { 1, 2 }
        };

var jaggedArray2 = new[]
        {
            new[] { 1, 2, 3 },
            new[] { 1, 2, 3, 4 }
        };

int[][][] jaggedArray = new[]
        {
            jaggedArray1,
            jaggedArray2
        };

you could just do,

var jaggedArray = new[]
        {
            new[]
                {
                    new[] { 1, 2, 3, 4 },
                    new[] { 1, 2, 3 },
                    new[] { 1, 2 }
                },

            new[]
                {
                    new[] { 1, 2, 3 },
                    new[] { 1, 2, 3, 4 }
                }
        };

The second pair of brackets indicates the dimensions. So it's like you are declaring a multi-dimensional array except you don't need to specify dimensions in the definition.You can initialize each array with different dimensions.

int[][,] jaggedArray = new int[3][,];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM