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.
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 }
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With