Unlock the Power of Foreach Loops in C#
The Syntax of Foreach Loops
A foreach loop consists of three main components: the iterable item (an array or collection), the iteration variable, and the in keyword. The syntax is simple yet powerful:
foreach (iteration variable in iterable item) { /* code to execute */ }
How Foreach Loops Work
On each iteration, the in keyword selects an item from the iterable item and stores it in the iteration variable. This process continues until all items have been processed, making it easy to iterate through large datasets.
A Side-by-Side Comparison: For vs Foreach Loops
Let’s put foreach loops to the test by comparing them to traditional for loops. In our first example, we’ll print an array using both methods.
Example 1: Printing an Array using For and Foreach Loops
// Using a for loop
int[] scores = { 10, 20, 30, 40, 50 };
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
// Using a foreach loop
int[] scores = { 10, 20, 30, 40, 50 };
foreach (int score in scores)
{
Console.WriteLine(score);
}
Both programs produce the same output, but the foreach loop stands out for its simplicity and ease of use.
Traversing Arrays with Foreach Loops
But foreach loops aren’t limited to simple printing tasks. In our next example, we’ll use a foreach loop to compute the number of male and female candidates in an array.
Example 2: Traversing an Array of Genders using Foreach Loop
string[] genders = { "male", "female", "male", "female", "male" };
int maleCount = 0;
int femaleCount = 0;
foreach (string gender in genders)
{
if (gender == "male")
{
maleCount++;
}
else
{
femaleCount++;
}
}
Console.WriteLine($"Males: {maleCount}, Females: {femaleCount}");
The output is clear: 3 males and 2 females. But what about collections?
Foreach Loops with Collections
In our final example, we’ll use a foreach loop to compute the sum of elements in a List.
Example 3: Foreach Loop with List (Collection)
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
Console.WriteLine($"Sum: {sum}");
With an output of 15, it’s clear that foreach loops are the way to go when working with collections.
Foreach loops offer a more readable, efficient, and expressive way to iterate through arrays and collections in C#. By embracing this powerful tool, developers can streamline their code and unlock new possibilities.