foreach Loop
The foreach loop in C# executes a block of code on each element in an array or a collection of items. When executing foreach loop it traversing items in a collection or an array. The foreach loop is useful for traversing each item in an array or a collection of items and displayed one by one. the foreach loop when working with arrays and collections to iterate through the items of arrays/collections. The foreach loop iterates through each item hence called foreach loop.
foreach(variable type in collection){
// code block
}
The in keyword used along with foreach loop is used to iterate over the iterable-item. The in keyword selects an item from the iterable-item on each iteration and store it in the variable element. On first iteration, the first item of iterable-item is stored in element. On second iteration, the second element is selected and so on. The number of times the foreach loop will execute is equal to the number of elements in the array or collection. Here is an example of iterating through an array using the for loop:
Example 1: Printing array using foreach loop
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("foreach loop Example!");
string[] name = new string[5] { "Shubham","Rahul","Mohit","Anmol","Sham"};
foreach (var num in name)
{
Console.WriteLine("Name - "+ num);
}
}
}
Output :
foreach loop Example!
Name - Shubham
Name - Rahul
Name - Mohit
Name - Anmol
Name - Sham
Example 2: Printing array using foreach loop
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("foreach loop Example!");
string[] name = new string[] { "Shubham Batra"};
foreach (var num in name)
{
if(num =="Shubham Batra")
{
Console.WriteLine("Hey - "+ num);
}
}
}
}
Output
foreach loop Example!
Hey - Shubham Batra