This example shows you how to use foreach loop in C#
As you know, Foreach statement executes a statement or a block of statements for each element in an instance of the type that implements the IEnumerable or IEnumerable<T> interface
var languages = new List<string>() { "C#", "C/C++", "Java", "SQL" };
foreach (string name in languages)
Console.WriteLine(name);
Foreach with continue statement
var names = new List<string>() { "Lucy", "Tom", "Jack", "John" };
foreach (string name in names)
{
if(name == "Tom")
continue;
Console.WriteLine(name);
}
If the continue statement is used within the loop body, it immediately switches to the next iteration ignoring the remaining code of the current iteration
Foreach with break statement
var numbers = new List<int>() { 1, 2, 3, 4, 5 };
foreach (string number in numbers)
{
if(number == 3)
break;
Console.WriteLine(number);
}
If the break statement is used in the loop, it stops the iteration loop and goes immediately after the loop