[英]How to add items to a jagged array?
I have a jagged array of type long[][]
. 我有一个
long[][]
整齐的数组,类型为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()
). 当然:如果经常需要调整数组大小,最好使用
List<List<T>
或Dict<long, List<long>>
除非有特殊原因需要使用数组(但即使这样,总会有.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. 在C#中,锯齿状数组也称为“数组数组”,因为其元素是数组。 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();
}
jagged array can declare & initialize in same line of code 锯齿状数组可以在同一行代码中声明和初始化
int[][] arr = new int[2][]{ int [] [] arr =新的int [2] [] {
new int[] { 11, 21, 56, 78 }, new int [] {11,21,56,78},
new int[] { 2, 5, 6, 7, 98, 5 } new int [] {2,5,6,7,98,5}
}; };
same things would be applicable for 'long' 同样的东西也适用于“长”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.