Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 581
Udit Saikia Avatar asked Mar 12 '26 09:03

Udit Saikia


1 Answers

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 }
                }
        };
like image 180
Jodrell Avatar answered Mar 14 '26 21:03

Jodrell