The foreach Loop
The C# foreach keyword allows you to iterate over all items within an array, without the need to test
for the array’s upper limit. Here are two examples using foreach, one to traverse an array of strings
and the other to traverse an array of integers:
// Iterate array items using foreach.
static void ForAndForEachLoop()
{
...
string[] carTypes = {"Ford", "BMW", "Yugo", "Honda" };
foreach (string c in carTypes)
Console.WriteLine(c);
int[] myInts = { 10, 20, 30, 40 };
foreach (int i in myInts)
Console.WriteLine(i);
}
In addition to iterating over simple arrays, foreach is also able to iterate over system-supplied
or user-defined collections. I’ll hold off on the details until Chapter 9, as this aspect of the foreach
keyword entails an understanding of interface-based programming and the role of the IEnumerator
and IEnumerable interfaces.
Do'stlaringiz bilan baham: |