In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc. It can be used with any type that implements the IEnumerable interface.
Syntax:
foreach (var item in collection)
{
//access item
}
The following example demonstrates iteration of an array using a foreach loop.
Example: Iterate an Array
Copy
string[] carCompanies = { 'Tata Motors', 'Mahindra', 'Volkswagen', 'Toyota' };
foreach(string car in carCompanies)
{
Console.WriteLine('{0}', car);
}
Output:
Tata Motors
Mahindra
Volkswagen
Toyota
The following example demonstrates the foreach loop on a list collection.
Example: Iterate a List
List<int> oddNumbers = new List<int>() { 1, 3, 5, 7, 9};
foreach(int num in oddNumbers)
{
Console.Write(num);
}
oddNumbers.ForEach(num => Console.Write(num)); //using ForEach extension method
Output.
13579
The System.Collections.Generic
namespace contains the ForEach()
extension method that can be used with any built-in collection classes such as List, Dictionary, SortedList, etc.
Important Points:
- The foreach loop iterate only in forward direction.
- Performance wise foreach loop takes much time as compared with for loop. Because internally it uses extra memory space as well as.
- The foreach loop use
GetEnumarator()
method of theIEnumerable
interface. So, the foreach loop can be used with any class that has implemented the interface. - Exit the foreach loop by using break, return, Goto and throw.
The following example demonstrates the foreach loop on a dictionary collection.