C# Foreach Loop Statements
In C#, the foreach
loop is used to iterate over elements of an array or items of a collection. The syntax for a foreach
loop is simple and easy to understand. It allows you to write more readable and maintainable code.
Syntax
The syntax for a foreach
loop in C# is as follows:
1foreach (var element in collection) 2{ 3 // statements 4}
In the above syntax, var element
is a variable that is used to hold each element of the collection, and collection
is the array or collection of items to be iterated. The foreach
loop will iterate over each element of the collection and execute the statements inside the loop.
Example
Here is an example of how to use a foreach
loop to iterate over the elements of an array:
1int[] numbers = { 1, 2, 3, 4, 5 }; 2 3foreach (var number in numbers) 4{ 5 Console.WriteLine(number); 6}
The above code will print the numbers 1 through 5 on separate lines.
Working with Collections
The foreach
loop is commonly used to iterate over collections such as lists, dictionaries, and other data structures. Here is an example of how to use a foreach
loop to iterate over a List
of strings:
1List<string> names = new List<string>() { "William", "Mary", "Steve" }; 2 3foreach (var name in names) 4{ 5 Console.WriteLine(name); 6}
The above code will print the names "William", "Mary", and "Steve" on separate lines.
Modifying Collections
In some cases, you may want to modify a collection while iterating over it. This can be done using a for
loop, but it can also be done using a foreach
loop if you are careful. Here is an example of how to use a foreach
loop to modify the elements of a List
of integers:
1List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 }; 2 3foreach (int number in numbers.ToList()) 4{ 5 if (number == 3) 6 { 7 numbers.Remove(number); 8 } 9} 10 11foreach (int number in numbers) 12{ 13 Console.WriteLine(number); 14}
In the above code, we use the ToList()
method to create a copy of the numbers
list. We then use the foreach
loop to iterate over this copy, and we remove the number 3
from the original list. This code will print the numbers 1
, 2
, 4
, and 5
on separate lines.