10 minlesson

Foreach Loops

Foreach Loops

The foreach loop provides the cleanest way to iterate over collections, arrays, and other enumerable types.

Basic foreach Syntax

csharp
1string[] fruits = { "Apple", "Banana", "Cherry" };
2
3foreach (string fruit in fruits)
4{
5 Console.WriteLine(fruit);
6}

Output

1Apple
2Banana
3Cherry

Syntax

csharp
1foreach (type variable in collection)
2{
3 // Use variable
4}
  • type: The type of elements in the collection
  • variable: A new variable that holds each element
  • collection: The array or collection to iterate over

Arrays with foreach

csharp
1int[] numbers = { 10, 20, 30, 40, 50 };
2
3foreach (int num in numbers)
4{
5 Console.WriteLine(num);
6}
7
8// Calculate sum
9int sum = 0;
10foreach (int num in numbers)
11{
12 sum += num;
13}
14Console.WriteLine($"Sum: {sum}"); // 150

Strings with foreach

Strings are sequences of characters:

csharp
1string message = "Hello";
2
3foreach (char c in message)
4{
5 Console.WriteLine(c);
6}
7// H
8// e
9// l
10// l
11// o

Count Vowels

csharp
1string text = "Hello World";
2int vowelCount = 0;
3
4foreach (char c in text.ToLower())
5{
6 if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
7 {
8 vowelCount++;
9 }
10}
11
12Console.WriteLine($"Vowels: {vowelCount}"); // 3

Using var

Let the compiler infer the type:

csharp
1var colors = new[] { "Red", "Green", "Blue" };
2
3foreach (var color in colors)
4{
5 Console.WriteLine(color);
6}

foreach is Read-Only

You cannot modify collection elements directly in foreach:

csharp
1int[] numbers = { 1, 2, 3 };
2
3foreach (int num in numbers)
4{
5 // num = num * 2; // Error! Cannot modify iteration variable
6}
7
8// To modify, use a for loop with index:
9for (int i = 0; i < numbers.Length; i++)
10{
11 numbers[i] = numbers[i] * 2; // OK
12}

Don't Modify Collection During foreach

Adding or removing items during iteration causes errors:

csharp
1List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
2
3// DON'T DO THIS - causes InvalidOperationException
4// foreach (int num in numbers)
5// {
6// if (num == 3)
7// numbers.Remove(num); // Error!
8// }
9
10// Instead, collect items to remove first:
11List<int> toRemove = new List<int>();
12foreach (int num in numbers)
13{
14 if (num == 3)
15 toRemove.Add(num);
16}
17foreach (int num in toRemove)
18{
19 numbers.Remove(num);
20}
21
22// Or use RemoveAll:
23numbers.RemoveAll(n => n == 3);

foreach vs for

When to Use foreach

  • Reading all elements in order
  • You don't need the index
  • Cleaner, more readable code

When to Use for

  • You need the index
  • You need to modify elements
  • You need to iterate in reverse
  • You need to skip elements
csharp
1string[] names = { "Alice", "Bob", "Charlie" };
2
3// foreach: simple iteration
4foreach (string name in names)
5{
6 Console.WriteLine(name);
7}
8
9// for: when you need the index
10for (int i = 0; i < names.Length; i++)
11{
12 Console.WriteLine($"{i + 1}. {names[i]}");
13}

Getting Index with foreach

If you need an index with foreach, use a manual counter or LINQ:

csharp
1string[] items = { "A", "B", "C" };
2
3// Manual counter
4int index = 0;
5foreach (string item in items)
6{
7 Console.WriteLine($"{index}: {item}");
8 index++;
9}
10
11// Using LINQ Select (more advanced)
12foreach (var (item, idx) in items.Select((value, i) => (value, i)))
13{
14 Console.WriteLine($"{idx}: {item}");
15}

Lists with foreach

csharp
1List<string> tasks = new List<string>
2{
3 "Buy groceries",
4 "Clean room",
5 "Do homework"
6};
7
8Console.WriteLine("To-Do List:");
9foreach (string task in tasks)
10{
11 Console.WriteLine($" [ ] {task}");
12}

Dictionaries with foreach

csharp
1Dictionary<string, int> ages = new Dictionary<string, int>
2{
3 { "Alice", 25 },
4 { "Bob", 30 },
5 { "Charlie", 35 }
6};
7
8// Iterate key-value pairs
9foreach (KeyValuePair<string, int> pair in ages)
10{
11 Console.WriteLine($"{pair.Key}: {pair.Value}");
12}
13
14// Or using var for cleaner code
15foreach (var pair in ages)
16{
17 Console.WriteLine($"{pair.Key} is {pair.Value} years old");
18}
19
20// Or deconstruct
21foreach (var (name, age) in ages)
22{
23 Console.WriteLine($"{name} is {age}");
24}

Practical Examples

Find Maximum

csharp
1int[] scores = { 85, 92, 78, 95, 88 };
2int max = scores[0];
3
4foreach (int score in scores)
5{
6 if (score > max)
7 {
8 max = score;
9 }
10}
11
12Console.WriteLine($"Highest score: {max}"); // 95

Search for Item

csharp
1string[] names = { "Alice", "Bob", "Charlie", "Diana" };
2string searchFor = "Charlie";
3bool found = false;
4
5foreach (string name in names)
6{
7 if (name == searchFor)
8 {
9 found = true;
10 break; // No need to continue searching
11 }
12}
13
14Console.WriteLine(found ? "Found!" : "Not found");

Combine Array Elements

csharp
1string[] words = { "Hello", "World", "from", "C#" };
2string sentence = "";
3
4foreach (string word in words)
5{
6 sentence += word + " ";
7}
8
9Console.WriteLine(sentence.Trim()); // Hello World from C#
10
11// Better: use string.Join
12string joined = string.Join(" ", words);
13Console.WriteLine(joined); // Hello World from C#

Summary

In this lesson, you learned:

  • foreach provides clean syntax for iterating over collections
  • Syntax: foreach (type item in collection)
  • You cannot modify collection elements directly
  • Don't add/remove items during iteration
  • Use for loops when you need the index or need to modify
  • Works with arrays, strings, lists, dictionaries, and more

Next, we'll learn about break and continue for controlling loop execution.