Книга: C# 2008 Programmer
foreach
foreach
One common use for the for loop is to iterate through a series of objects in a collection. In C# there is another looping construct that is very useful for just this purpose — the foreach statement, which iterates over each element in a collection. Take a look at an example:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in nums) {
Console.WriteLine(i);
}
This code block prints out all the numbers in the nums array (from 1 to 9). The value of i
takes on the value of each individual member of the array during each iteration. However, you cannot change the value of i
within the loop, as the following example demonstrates:
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int i in nums) {
i += 4; //---error: cannot change the value of i---
Console.WriteLine(i);
}
Here is another example of the use of the foreach loop:
string[] words = { "C#", "3.0", "Programming", "is", "fun" };
foreach (string w in words) {
Console.WriteLine(w);
}
This code block prints out:
C#
3.0
Programming
is
fun