Foreach Loop with examples.
Notes from this video:
Foreach Loop-
The foreach loop is used to iterate through the elements of a collection, such as an array, list, or other enumerable types. It's particularly useful when we need to access each element in a collection without knowing or caring about the size/length of the collection. Here's an overview and examples of how to use the foreach
Basic Syntax
foreach (var element in collection) { // Code to be executed for each element }
• element: This is a variable that represents the current element in the collection.
• collection: This is the collection you want to iterate over.
Example 1: Iterating Through an Array
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
In this example, the foreach loop iterates through each element in the numbers array and prints it.
Example 2: Iterating Through a List
List〈string〉 names = new List〈string〉 { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
Console.WriteLine(name);
}
In this example, the foreach loop iterates through each element in the names list and prints it.
Example 3: Iterating Through a Dictionary
Dictionary〈int, string〉 keyValuePairs = new Dictionary〈int, string〉 { { 1, "One" }, { 2, "Two" }, { 3, "Three" } };
foreach (KeyValuePair〈int, string〉 kvp in keyValuePairs)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
In this example, the foreach loop iterates through each key-value pair in the keyValuePairs dictionary and prints the key and value.
Example 4: Iterating Through a String
string message = "Hello, World!";
foreach (char ch in message)
{
Console.Write(ch + " ");
}
In this example, the foreach loop iterates through each character in the message string and prints it with a space.
Example 5: Using foreach with LINQ
We can use LINQ to create queries and then iterate through the results with a foreach loop.
List〈int〉 numbers = new List〈int〉 { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n =〉 n % 2 == 0);
foreach (int evenNumber in evenNumbers) { Console.WriteLine(evenNumber); }
In this example, the foreach loop iterates through the even numbers filtered by the LINQ query.
Benefits of foreach Loop
• Simplicity: The foreach loop is simpler to write and read, especially for collections.
• Safety: It avoids common errors related to index management.
• Clarity: The intent of iterating over a collection is clear and concise.