C# foreach

The foreach statement is actually one of the loop statements. It will go through all elements of a collection and assign a variable to the element for each iteration and you can add code to process it. Array is one of the collections and foreach statement can be used to loop each element of it.

Syntax:

foreach ( <Element Data Type> <Variable Name> in <Collection Name> ) {
	...
}

"foreach" and "in" are reserved keywords in C#.

<Element Data Type> must be matched with the type of the elements in the collection.

<Variable Name> is the variable which hold current element for each iteration.

<Collection Name> is the collection variable which can be an array or other collection. We'll introduce the other collections in our later sections.

We know For Loop is one of loop statements in C# and it is often used whenever you know loop times in the code. The foreach statement provides a light way to loop each element without knowing the loop times.

Example 01-80-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class TestForeach1
{
    static void Main()
    {
        string[] s = { "One", "Two", "Three", "Four", "Five" };

        for (int i = 0; i < s.Length; i++)
        {
            Console.Write("{0} ", s[i]);
        }
        Console.WriteLine();

        foreach (string str in s)
        {
            Console.Write("{0} ", str);
        }
        Console.WriteLine();

        Console.Read();
    }
}

Output

One Two Three Four Five 
One Two Three Four Five 

Explanation

  • Line 8: Declare a string array with initialized 5 elements.
  • Line 10-14: Output each element in for statement.
  • Line 16-19: Output each element in foreach statement. For each iteration the current element is assigned to str. You can see s is a string array so the variable str must be declared as string.
  • Line 18: Output the element. Pay attention, we're using str to represent the current element rather than s[str].

Like the other loop statements, break and continue statement can be used in foreach statement as well.

Example 01-80-02

In this example, we'll output the positive numbers of the array until the sum of them reaches 30.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;

class TestForeach2
{
    static void Main()
    {
        int[] a = { 1, 2, -1, 0, 3, -4, -2, 4, 5, 6, -9, 9, -7, 10 };
        int total = 0;

        foreach (int i in a)
        {
            if (i <= 0) continue;
            if (total + i <= 30)
            {
                Console.Write("{0} ", i);
                total += i;
            }
            else
            {
                break;
            }            
        }
        Console.WriteLine();
        Console.WriteLine("Total: {0}", total);

        Console.Read();
    }
}

Output

1 2 3 4 5 6 9 
Total: 30

Explanation

  • Line 7: Declare an integer array with initialization.
  • Line 10: Start foreach statement to loop all the elements. For each iteration the current element is assigned to i. You can see a is an integer array so i must be declared as int.
  • Line 12: Filter out the zero and negative numbers by using continue statement.
  • Line 13-21: if the totals is less or equal than 30 after adding up the current number, we'll output the number and add it to the total. Otherwise we'll use break statement to get out of the loop.
  • Line 24: At last output the total number.