foreach inside foreach c# code example

Example 1: foreach syntax c#

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Example 2: The foreach Loop c#

string[] names = {"William.", "James", "Oliver", "Lucas"};
foreach (string i in names) 
{
  Console.WriteLine(i);
}

Example 3: for each c#

var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 };
int count = 0;
foreach (int element in fibNumbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");

Example 4: syntax foreach loop C#

foreach (type variableName in arrayName) 
{
  // code block to be executed
}