c# foreach array code example

Example 1: c# loop through array

//iterate the array
for (int i = 0; i < arr.Length; i++)
{
  // loop ...
}
// or
foreach (var element in arr)
{
  // loop ...
}

Example 2: 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 3: c# loop through array

int[] numberArray = { 4, 5, 6, 1, 2, 3, -2, -1, 0 };
foreach (int number in numberArray)
{
    System.Console.Write("{0} ", number);
}

Example 4: c# foreach arra

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };

foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55

Example 5: c# foreach

var numbers = new NumberList<int> { 0, 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    DoSomething();
}

Example 6: c# foreach

foreach (int num in numbers)
{
  
}