The foreach loop in C# is a control flow statement that iterates over a collection or array, executing a block of code for each element in the collection. It provides a simple, readable way to loop through elements without needing to manage the loop control variable manually.
Structure of a foreach Loop
The basic structure of a foreach loop includes:
The foreach keyword followed by parentheses ().
Inside the parentheses, specify the element type and a variable to represent each element, followed by the in keyword and the collection to be iterated over.
A block of code enclosed in curly braces {} that will be executed for each element in the collection.
Following is the syntax for a foreach loop in C#:
foreach (elementTypeelementincollection) { // Code to be executed for each element }
Initialization: We define an array numbers containing the integers 1 through 6.
foreach Loop: The foreach loop iterates over each element in the numbers array.
The int number part declares a variable number of type int that represents each element in the array.
The in numbers part specifies that the loop should iterate over the numbers array.
Loop Body: Inside the loop, Console.WriteLine(number) prints the current element (number) to the console.
Use Cases for foreach Loops
Iterating Over Collections: Simplifying the process of iterating over collections like arrays, lists, and dictionaries.
Processing Data: Performing operations on each element in a collection, such as summing numbers, filtering data, or transforming elements.
Reading Data: Reading data from collections without modifying the collection.
Nested foreach Loops
foreach loops can also be nested to handle more complex scenarios. For instance, consider a program that iterates over a two-dimensional array (matrix) and prints each element: