How to add items/elements to an existing jagged array in C#?

CsharpProgrammingServer Side Programming

To add an element to existing jagged array, just set the value of the element with a new value.

Let’s say you need to add an element at the following location −

a[3][1]

Just set the value −

a[3][1] = 500;

Above, we accessed the first element of the 3rd array in a jagged array.

Let us see the complete code −

Example

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {

         int[][] x = new int[][]{new int[]{10,20},new int[]{30,40}, new int[]{50,60},new int[]{ 70, 80 }, new int[]{ 90, 100 } };
         int i, j;

         Console.WriteLine("Old Array...");
         for (i = 0; i < 5; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, x[i][j]);
            }
         }

         x[3][1] = 500;

         Console.WriteLine("New Array...");
         for (i = 0; i < 5; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, x[i][j]);
            }
         }
         Console.ReadKey();
      }
   }
}
raja
Published on 14-Aug-2018 11:03:11
Advertisements