The for each loop is used to execute a block of code for each object inside a collection.
Example:
public static void Main()
{
var books = new String[] { "Harry Potter", "Lord of the Rings" };
foreach (var book in books)
{
Console.WriteLine(book);
}
}
Firstly, we initialize a new variable books with a new array of strings containing two elements "Harry Potter" and "Lord of the Rings".Then we're using the foreach loop to iterate over each element of the books array. The temporary variable book will contain the current element of the collection that we are iterating. We can use the Console.WriteLine() method to display this element inside of the console windows.
The result:
Harry Potter
Lord of the Rings