简体   繁体   中英

How to add items to a jagged array?

I have a jagged array of type long[][] .

This might be simple, but I can't seem to figure how to add values to the end of the array.

Do I need to resize it before and how do I actually add items?

A jagged array is basically an array of arrays. You need to resize the array you want to add an element to:

var array = new long[][]
{
    new long[]{1},
    new long[]{2,3}
};

// change existing element
array[1][0]=0;

// add row & fill it
Array.Resize(ref array, 3);
Array.Resize(ref array[2], 1);
array[2][0]=5;

// resize existing row

Array.Resize(ref array[1], 3);
array[1][2]=6;

Of course: if you frequently need to resize your arrays, you might be better of using a List<List<T> or a Dict<long, List<long>> unless there is a specific reason you need to work with arrays (but even then there is always .ToArray() ). One use case for using a jagged array and resizing it, would be access performance in arrays with with many elements.

In C#, jagged array is also known as "array of arrays" because its elements are arrays. The element size of jagged array can be different.

int[][] arr = new int[2][];// Declare the array      
int[] arr1 = new int[4];
int[] arr2 = new int[6];    
//user input for arr1
for (int i = 0; i < arr1.Length;i++ )
{
    arr1[i] = int.Parse(Console.ReadLine());
}    
// user input for arr2
for (int i = 0; i < arr2.Length; i++)
{
    arr2[i] = int.Parse(Console.ReadLine());
}    
arr[0] = arr1;
arr[1] = arr2;            
// Traverse array elements  
for (int i = 0; i < arr.Length; i++)
{
    for (int j = 0; j < arr[i].Length; j++)
    {
        System.Console.Write(arr[i][j] + " ");
    }
    System.Console.WriteLine();
}
  • int[][] arr = new int[2][] for declare jagged array , 2 represent number arrays it will hold. 'arr' array holds 'arr1' & 'arr2'
  • jagged array can declare & initialize in same line of code

    int[][] arr = new int[2][]{
    new int[] { 11, 21, 56, 78 },
    new int[] { 2, 5, 6, 7, 98, 5 }
    };

  • same things would be applicable for 'long'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM