For Each Loop

In this lession we will learn about foreach loop, foreach loop is an alternative of for loop. We will also learn how to use foreach loop for an array and collection or list object.

When you know how many number of times we want to iterate the loop then you can use for loop, but when there is no specific number of iterations then foreach loop can be used.

Syntax

In syntax of foreach loop we need to give an array, list of any iteratable item, and need to define variable of item that exists in the collection. For exmaple

Try it
foreach (element in iterable-item)
{
	// code block to executes
}

foreach loop with Array

Try it
string[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
foreach (string dayName in weekdays)
{
    Console.WriteLine("{0} is weekday", dayName);
}
//Output
Monday is weekday
Tuesday is weekday
Wednesday is weekday
Thursday is weekday
Friday is weekday

Foreach loop is more readable and easy to understand than for loop due to it's easy syntax. In above example we have seen foreach loop with an array, now in below example we will see how to iterate within list using foreach loop. For example

foreach loop with List

Try it
List weekends = new List { "Saturday", "Sunday" };
foreach (string dayName in weekends)
{
    Console.WriteLine("{0} is weekend", dayName);
}
//Output
// Saturday is weekend
// Sunday is weekend

 

← Previous

Next →