Share via


Using foreach with Arrays (C# Programming Guide)

C# also provides the foreach statement. This statement provides a simple, clean way to iterate through the elements of an array or any enumerable collection. The foreach statement processes elements in the order returned by the array or collection type’s enumerator, which is usually from the 0th element to the last. For example, the following code creates an array called numbers and iterates through it with the foreach statement:

int[] numbers = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int i in numbers)
{
    System.Console.Write("{0} ", i);
}
// Output: 4 5 6 1 2 3 -2 -1 0

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form: 
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } }; 

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

However, with multidimensional arrays, using a nested for loop gives you more control over the array elements.

See Also

Reference

Arrays (C# Programming Guide)

Single-Dimensional Arrays (C# Programming Guide)

Multidimensional Arrays (C# Programming Guide)

Jagged Arrays (C# Programming Guide)

Array

Concepts

C# Programming Guide