Foreach Loops
The foreach loop provides the cleanest way to iterate over collections, arrays, and other enumerable types.
Basic foreach Syntax
csharp1string[] fruits = { "Apple", "Banana", "Cherry" };23foreach (string fruit in fruits)4{5 Console.WriteLine(fruit);6}
Output
1Apple2Banana3Cherry
Syntax
csharp1foreach (type variable in collection)2{3 // Use variable4}
- 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
csharp1int[] numbers = { 10, 20, 30, 40, 50 };23foreach (int num in numbers)4{5 Console.WriteLine(num);6}78// Calculate sum9int 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:
csharp1string message = "Hello";23foreach (char c in message)4{5 Console.WriteLine(c);6}7// H8// e9// l10// l11// o
Count Vowels
csharp1string text = "Hello World";2int vowelCount = 0;34foreach (char c in text.ToLower())5{6 if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')7 {8 vowelCount++;9 }10}1112Console.WriteLine($"Vowels: {vowelCount}"); // 3
Using var
Let the compiler infer the type:
csharp1var colors = new[] { "Red", "Green", "Blue" };23foreach (var color in colors)4{5 Console.WriteLine(color);6}
foreach is Read-Only
You cannot modify collection elements directly in foreach:
csharp1int[] numbers = { 1, 2, 3 };23foreach (int num in numbers)4{5 // num = num * 2; // Error! Cannot modify iteration variable6}78// To modify, use a for loop with index:9for (int i = 0; i < numbers.Length; i++)10{11 numbers[i] = numbers[i] * 2; // OK12}
Don't Modify Collection During foreach
Adding or removing items during iteration causes errors:
csharp1List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };23// DON'T DO THIS - causes InvalidOperationException4// foreach (int num in numbers)5// {6// if (num == 3)7// numbers.Remove(num); // Error!8// }910// 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}2122// 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
csharp1string[] names = { "Alice", "Bob", "Charlie" };23// foreach: simple iteration4foreach (string name in names)5{6 Console.WriteLine(name);7}89// for: when you need the index10for (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:
csharp1string[] items = { "A", "B", "C" };23// Manual counter4int index = 0;5foreach (string item in items)6{7 Console.WriteLine($"{index}: {item}");8 index++;9}1011// 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
csharp1List<string> tasks = new List<string>2{3 "Buy groceries",4 "Clean room",5 "Do homework"6};78Console.WriteLine("To-Do List:");9foreach (string task in tasks)10{11 Console.WriteLine($" [ ] {task}");12}
Dictionaries with foreach
csharp1Dictionary<string, int> ages = new Dictionary<string, int>2{3 { "Alice", 25 },4 { "Bob", 30 },5 { "Charlie", 35 }6};78// Iterate key-value pairs9foreach (KeyValuePair<string, int> pair in ages)10{11 Console.WriteLine($"{pair.Key}: {pair.Value}");12}1314// Or using var for cleaner code15foreach (var pair in ages)16{17 Console.WriteLine($"{pair.Key} is {pair.Value} years old");18}1920// Or deconstruct21foreach (var (name, age) in ages)22{23 Console.WriteLine($"{name} is {age}");24}
Practical Examples
Find Maximum
csharp1int[] scores = { 85, 92, 78, 95, 88 };2int max = scores[0];34foreach (int score in scores)5{6 if (score > max)7 {8 max = score;9 }10}1112Console.WriteLine($"Highest score: {max}"); // 95
Search for Item
csharp1string[] names = { "Alice", "Bob", "Charlie", "Diana" };2string searchFor = "Charlie";3bool found = false;45foreach (string name in names)6{7 if (name == searchFor)8 {9 found = true;10 break; // No need to continue searching11 }12}1314Console.WriteLine(found ? "Found!" : "Not found");
Combine Array Elements
csharp1string[] words = { "Hello", "World", "from", "C#" };2string sentence = "";34foreach (string word in words)5{6 sentence += word + " ";7}89Console.WriteLine(sentence.Trim()); // Hello World from C#1011// Better: use string.Join12string 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.