Information Technology Reference
In-Depth Information
Example with a Jagged Array
Since jagged arrays are arrays of arrays, separate foreach statements must be used for each
dimension in the jagged array. The foreach statements must be nested properly to make sure
that each nested array is processed properly.
For example, in the following code, the first foreach statement cycles through the top-level
array— arr1 —selecting the next sub-array to process. The inner foreach statement processes
the elements of that sub-array.
static void Main()
{
int nTotal = 0;
int[][] arr1 = new int[2][];
arr1[0] = new int[] { 10, 11 };
arr1[1] = new int[] { 12, 13, 14 };
foreach (int[] array in arr1) // Process the top level.
{
Console.WriteLine("Starting new array");
foreach (int item in array) // Process the second level.
{
nTotal += item;
Console.WriteLine(" Item: {0}, Current Total: {1}", item, nTotal);
}
}
}
The output is the following:
Starting new array
Item: 10, Current Total: 10
Item: 11, Current Total: 21
Starting new array
Item: 12, Current Total: 33
Item: 13, Current Total: 46
Item: 14, Current Total: 60
Search WWH ::




Custom Search