Add item to jagged array

I have already covered several array topics, but I'm still at a standstill.

I want to add a new line to my jagged array - and I want the syntax to be correct ..

int[][] intJaggedArray = new int[7][]; intJaggedArray[0] = new int[3] { 1, 1, 1 }; intJaggedArray[1] = new int[3] { 2, 2, 2 }; intJaggedArray[2] = new int[3] { 3, 3, 3 }; intJaggedArray[3] = new int[3] { 4, 4, 4 }; intJaggedArray[4] = new int[3] { 5, 5, 5 }; intJaggedArray[5] = new int[3] { 6, 6, 6 }; intJaggedArray[6] = new int[3] { 7, 7, 7 }; 

So, if I want to add

  intJaggedArray[0] = new int[3] { 1, 1, 2 }; 

so the array ends as shown below, as I understand it - in advance - A noob from England. (And many thanks in advance)

  intJaggedArray[0] = new int[3] { 1, 1, 1 }; intJaggedArray[0] = new int[3] { 1, 1, 2 }; intJaggedArray[1] = new int[3] { 2, 2, 2 }; intJaggedArray[2] = new int[3] { 3, 3, 3 }; intJaggedArray[3] = new int[3] { 4, 4, 4 }; intJaggedArray[4] = new int[3] { 5, 5, 5 }; intJaggedArray[5] = new int[3] { 6, 6, 6 }; intJaggedArray[6] = new int[3] { 7, 7, 7 }; 
+4
source share
3 answers

What do you want to do? Insert row from 0 to 1? Or replace the existing string 0?

Your line:

 intJaggedArray[0] = new int[3] { 1, 1, 2 }; 

just replaces the existing string 0.

You cannot insert a string into an array. To do this, use the list instead:

 List<int[]> myList = new List<int[]>(); myList.Add(new int[] {...}); myList.Add(new int[] {...}); myList.Add(new int[] {...}); ... myList.Insert(1, new int[] {...}); 

Or, if you want to replace an existing string, simply:

+2
source

You might want to create a collection or List<int[]>

Then you can insert an element into it with a specific index.

 List<int[]> x = new List<int[]>(); x.Insert(3, new int[3] { 1, 2, 3 }); 
+2
source

If you want the source list to be of variable length, you cannot use an array. Use the List instead.

This should work:

 List<int[]> intJaggedList = new List<int[]>(); intJaggedList.Add( new int[3] { 1, 1, 1 } ); intJAggedList.Add( new int[3] { 2, 2, 2 } ); ... 

Then, to insert a new array:

 intJaggedList.Insert( 1, new int[3] { 1, 1, 2 } ); 
+1
source

Source: https://habr.com/ru/post/1344576/


All Articles