C# foreach loop

C# foreach tutorial image

What is foreach loop in C#?

The C# foreach statement is used to iterate through the elements of collections, arrays, etc.
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
 {
   Console.WriteLine(number);
}

You may execute a single statement or a block of statements for each element as using the foreach statement.

General structure for using the foreach:

foreach (element in iterable-item)

{

    // statement(s) to be executed

}

The example of foreach with an array

To explain how foreach works, we have an array of four elements. This is a numeric array and a value is assigned to each element.

A foreach loop is used and that array is specified.

A simple statement is used to display the current element’s value in each iteration:

using System;

namespace csharp_example
{
    class Program
    {
        static void Main(string[] args)

        {

            int[] numarray = new int[4];
            numarray[0] = 2;
            numarray[1] = 4;
            numarray[2] = 6;
            numarray[3] = 8;

            foreach (int x in numarray)
            {
                Console.WriteLine("Element Value = " + x);
            }
            Console.ReadLine();
        }
    }
}

The output of the above code:

Element Value = 2
Element Value = 4
Element Value = 6
Element Value = 8
Info: Where you may use foreach statement? An instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface e.g. List. You may also use foreach with the instance of any type that has the public parameterless GetEnumerator method.

The example of using foreach with a list

Similarly, you may use the foreach loop to iterate through the list collection in C#.

In the example below, we have created a list of numeric items.Then, a foreach loop is used to iterate through the listnums.

In foreach loop, we will display the current list item by Console.WriteLine statement.

Have a look:

using System;

using System.Collections.Generic;

namespace csharp_demo
{
    class Program
    {

        static void Main(string[] args)
        {

            List<int> listnums = new List<int>();

            listnums.Add(7);
            listnums.Add(9);
            listnums.Add(11);
            listnums.Add(13);
            listnums.Add(15);

            foreach (int y in listnums)
            {
                Console.WriteLine("The list item: " + y);
            }
            Console.ReadLine();
        }
    }
}

The output:

The list item: 7
The list item: 9
The list item: 11
The list item: 13
The list item: 15

An example of leap year using foreach

For this example, a list of years is created. The list is assigned nine years (from 1992 to 2108).

This is followed by using the foreach statement where C# if statement is used and each year is checked whether it is a leap year or not.

The code:

using System;

using System.Collections.Generic;

namespace csharp_example
{
    class Program
    {
        static void Main(string[] args)
        {
            var leap_list = new List<int> {1992, 1994, 1998, 2001, 2004, 2008, 2014, 2016, 2018 };

            foreach (int y in leap_list)
            {
                if (y % 4 == 0)
                {
                    Console.WriteLine(y + " is a Leap year");
                }
            }
            Console.ReadLine();
        }
    }
}

The output:

1992 is a Leap year
2004 is a Leap year
2008 is a Leap year
2016 is a Leap year

You can see that the list contains the following years:

1992, 1994, 1998, 2001, 2004, 2008, 2014, 2016, 2018

The program returned the leap years only.

Note: Leap year has two other conditions:

  • (i) Year is not divisible by 100. For example, 1900 is not a leap year, although it can be divided by 4.
  • (ii)Year can be divided by 400 is a leap year. For example, 2000 is a leap year as it can be divided by 400 (though it can be divided by 100 as well).
  • (iii)You need to incorporate these two conditions as well in the above code by using if..else if ladder etc.

Exit foreach with a break statement

At any point, you may exit the foreach loop by using the break statement.

To show how the break statement in foreach works, we have a list of five elements.

As the current element value is equal to 15, the break statement executes inside the foreach that exits the foreach loop:

using System;

using System.Collections.Generic;

namespace csharp_example

{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list_break = new List<int>();

            list_break.Add(0);
            list_break.Add(5);
            list_break.Add(10);
            list_break.Add(15);
            list_break.Add(20);

            foreach (int y in list_break)
            {
                if (y == 15)
                {
                    Console.WriteLine("The list element value is 15 so I will omit ");
                    break;
                }

                Console.WriteLine("The list item: " + y);
            }
            Console.ReadLine();
        }
    }
}

c# foreach-break

You can see, as the value of the list item is 15, the if statement was evaluated as true and it executed the break statement that terminated the foreach.

The example of using continue statement

The following example uses the continue statement for omitting the current iteration in foreach loop. Again, we have a numeric array of six elements and execute the foreach loop.

The array contains the following elements:

5, 7, 9, 11, 13, 15

Inside the foreach, the current element is displayed by Console.WriteLine method. However, as it reaches the number 13, the continue statement executes and we will not display that value. Have a look:

using System;
namespace csharp_example

{
    class Program
    {
        static void Main(string[] args)
        {
            int[] cont_array = new int[] { 5, 7, 9, 11, 13, 15 };
            foreach (int x in cont_array)
            {
                if (x == 13) {
                    continue;
                }
                Console.WriteLine("Element Value = " + x);
            }
            Console.ReadLine();
        }
    }
}

Output:

Element Value = 5
Element Value = 7
Element Value = 9
Element Value = 11
Element Value = 15

You can see, all elements are displayed except the number 13.

To omit the current iteration, we can use the C# continue statement.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!