什么是锯齿状数组(在 C# 中)?任何示例以及何时应该使用它....
7 回答
锯齿状数组是数组的数组。
string[][] arrays = new string[5][];
这是五个不同字符串数组的集合,每个数组的长度可能不同(它们也可能是相同的长度,但不能保证它们是相同的)。
arrays[0] = new string[5];
arrays[1] = new string[100];
...
这与矩形的二维数组不同,这意味着每行具有相同的列数。
string[,] array = new string[3,5];
锯齿状数组在任何语言中都是相同的,但它是您在第二个和超出数组中具有不同数组长度的二维数组的地方。
[0] - 0, 1, 2, 3, 4
[1] - 1, 2, 3
[2] - 5, 6, 7, 8, 9, 10
[3] - 1
[4] -
[5] - 23, 4, 7, 8, 9, 12, 15, 14, 17, 18
尽管问题所有者选择了最佳答案,但我仍然想提供以下代码以使锯齿状数组更加清晰。
using System;
class Program
{
static void Main()
{
// 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();
}
}
}
输出将是
1 2
0
3 4 5
锯齿状数组用于将数据存储在不同长度的行中。
有关更多信息,请查看MSDN 博客上的这篇文章。
您可以在此处找到更多信息:http: //msdn.microsoft.com/en-us/library/2s05feca.aspx
还 :
锯齿状数组是其元素为数组的数组。锯齿状数组的元素可以具有不同的维度和大小。锯齿状数组有时称为“数组数组”。以下示例展示了如何声明、初始化和访问交错数组。
下面是一个包含三个元素的一维数组的声明,每个元素都是一个整数的一维数组:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
或者
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
锯齿状数组是您在声明期间声明行数但在运行时或也由用户选择声明列数的数组,当您希望每个 JAGGED 数组中的不同列数适合这种情况时,它的平均值
int[][] a = new int[6][];//its mean num of row is 6
int choice;//thats i left on user choice that how many number of column in each row he wanna to declare
for (int row = 0; row < a.Length; row++)
{
Console.WriteLine("pls enter number of colo in row {0}", row);
choice = int.Parse(Console.ReadLine());
a[row] = new int[choice];
for (int col = 0; col < a[row].Length; col++)
{
a[row][col] = int.Parse(Console.ReadLine());
}
}
锯齿状数组是一个包含其他数组的数组。
锯齿状数组是行数固定但列数不固定的数组。
用于窗口窗体应用程序的 C# 中锯齿状数组的代码
int[][] a = new int[3][];
a[0]=new int[5];
a[1]=new int[3];
a[2]=new int[1];
int i;
for(i = 0; i < 5; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 3; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
for(i = 0; i < 1; i++)
{
a[0][i] = i;
ListBox1.Items.Add(a[0][i].ToString());
}
正如您在上面的程序中看到的那样,行数固定为 3,但列数不固定。所以我们取了三个不同的列值,即 5、3 和 1。ListBox1
这段代码中使用的关键字是我们将在窗口窗体中使用的列表框,通过单击按钮查看结果,该按钮也将用于窗口形式。此处完成的所有编程都在按钮上。
锯齿状数组是具有不同行数的多维数组。