How to Use the foreach Statement in C#
This tutorial describes how to use the foreach statement with examples in C#.
The foreach statement executes a block of code for each element of a given collection, such as a list, dictionary, or array.
Related C# tutorials:
The foreach Syntax
The syntax of the foreach statement is as follows:
foreach (element in collection) { //block of code }
Examples
Example 1
You can use the foreach statement to loop through a block of code for each number in a list, as the following code shows:
using System; using System.Collections.Generic; namespace ForeachExample { class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; foreach (int number in numbers) { Console.WriteLine(number); } } } }
Output:
1 2 3 4 5 6 7 8 9 10
Example 2
The following example shows how to execute a block of code for each number in an array:
using System; namespace ForeachExample { class Program { static void Main(string[] args) { int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; foreach (int number in numbers) { Console.WriteLine(number); } } } }
Output:
1 2 3 4 5 6 7 8 9 10
Example 3
The following code executes a block of code for each student in a list and prints it out to the console
using System; using System.Collections.Generic; namespace ForeachLoopExample { class Program { static void Main(string[] args) { List<string> students = new List<string> { "Student A", "Student B", "Student C", "Student C", "Student D", "Student E" }; foreach (string student in students) { Console.WriteLine(student); } } } }
Output:
Student A Student B Student C Student C Student D Student E
Example 4
The following example shows how to loop over a dictionary using the foreach statement:
using System; using System.Collections.Generic; namespace ForeachLoopExample { class Program { static void Main(string[] args) { Dictionary<int, string> dict = new Dictionary<int, string> { {1, "A" }, {2, "B" }, {3, "C" }, {4, "D" }, {5, "E" }, {6, "F" }, }; // foreach (KeyValuePair<int, string> d in dict) { Console.WriteLine("Key:" + d.Key + " " + "Value: " + d.Value); } Console.WriteLine("++++++++++++++++++++++++++++++"); // foreach (int key in dict.Keys) { Console.WriteLine("Key:" + key); } Console.WriteLine("++++++++++++++++++++++++++++++"); // foreach (string value in dict.Values) { Console.WriteLine("Value:" + value); } Console.WriteLine("++++++++++++++++++++++++++++++"); } } }
Output:
Key:1 Value: A Key:2 Value: B Key:3 Value: C Key:4 Value: D Key:5 Value: E Key:6 Value: F ++++++++++++++++++++++++++++++ Key:1 Key:2 Key:3 Key:4 Key:5 Key:6 ++++++++++++++++++++++++++++++ Value:A Value:B Value:C Value:D Value:E Value:F ++++++++++++++++++++++++++++++
More tutorials:
In this tutorial, you've learned how to use the foreach statement. The foreach statement allows you to loop through a block of code for each element in a list, array, or dictionary.