How to create jagged arrays in c#?
16,786
Solution 1
Official tutorial. Basically you create the "outer" array first, and then loop trough it, and create each "inner"array individually.
Two examples:
int[][] a = new int[] { new int[]{ 1, 2 }, new int[]{ 3, 4, 5, 6, 7 }};
int[][] c = new int[100][];
for (int i = 0; i < c.length; i++) c[i] = new int[5];
If you need only a 2D rectangular array, you can use int[,] b = new int[10, 7];
.
Solution 2
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
or
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
See Jagged Arrays (C# Programming Guide)
Solution 3
I don't know that in C but in c# you can use jagged arrays like:
// Declare local jagged array with 3 rows.
int[][] jagged = new int[3][];
// Create a new array in the jagged array, and assign it.
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[0][1] = 2;
// Set second row, initialized to zero.
jagged[1] = new int[1];
// Set third row, using array initializer.
jagged[2] = new int[3] { 3, 4, 5 };
// Print out all elements in the jagged array.
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write(innerArray[a] + " ");
}
Console.WriteLine();
}
http://www.dotnetperls.com/jagged-array
Related videos on Youtube
Author by
user1439564
Updated on October 15, 2022Comments
-
user1439564 about 1 year
I'm familiar with C. Where I can write like this:
uint array[0xFFFF][20];
But I've no idea how to do this in Csharp. I tried all MS tutorials and other tutorials but no luck.
Can someone please help me out?
-
Security Hound over 11 yearsYour syntax is all wrong. The only array you fill is the first array.
-
user1439564 over 11 yearsYes, I've seen that implementation. But if I use that, and say my inner array has elements of 100, i've to write down that sentence 100 times. Correct?
-
user1439564 over 11 yearsI've just came across this: data[,] = new uint[0xFFFF, 20]; it appears that that does the trick.
-
Matzi over 11 yearsSure it does, that is what I mentioned at the and as rectangular 2D array.
-
JasonMArcher almost 9 yearsHello and welcome to Stack Overflow. Code only answers are usually not very useful unless they explain what they do. This is very true of long segments of code. Please consider adding an explanation of what you changed or wrote.
-
Adiii almost 9 years@matzi your first line is incorrect dear ,you can also try ,you wrote new int[] while this is error.this one is correct for internalize jagged array int[][] a = new int[][] { new int[]{ 1, 2 }, new int[]{ 3, 4, 5, 6, 7 }};