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.
foreach (var item in collection)
{
//access item
}
The following example demonstrates iteration of an array using a foreach loop.
string[] carCompanies = { "Tata Motors", "Mahindra", "Volkswagen", "Toyota" };
foreach(string car in carCompanies)
{
Console.WriteLine("{0}", car);
}
Mahindra
Volkswagen
Toyota
The following example demonstrates the foreach loop on a list collection.
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
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.
var citiesOfCountry = new Dictionary<string, string>()
{
{"UK", "London, Manchester, Birmingham"},
{"USA", "Chicago, New York, Washington"},
{"India", "Mumbai, New Delhi, Pune"}
};
foreach(var city in citiesOfCountry)
{
Console.WriteLine("{0}, {1}", city.Key, city.Value);
}
USA, Chicago, New York, Washington,
India, Mumbai, New Delhi, Pune
Implement IEnumerable Interface
As mentioned before, the foreach loop can be used to iterate any class that has implemented the IEnumerable
interface.
The following example demonstrates how to implement the IEnumerable
interface in order to use the foreach loop with the custom class.
using System;
using System.Collections;
using System.Collections.Generic;
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
class Shop : IEnumerable
{
private Customer[] custArray = new Customer[4];
public Shop()
{
custArray[0] = new Customer() { Id = 1, Name = "Steve" };
custArray[1] = new Customer() { Id = 2, Name = "Paul" };
custArray[2] = new Customer() { Id = 3, Name = "Joe" };
custArray[3] = new Customer() { Id = 4, Name = "Yash" };
}
//Here implementation for the GetEnumerator method.
public IEnumerator GetEnumerator()
{
return custArray.GetEnumerator();
}
}
class Program
{
public static void Main(string[] args)
{
Shop objShop = new Shop();
foreach (Customer cust in objShop)
{
Console.WriteLine(cust.Name);
}
}
}
Paul
Joe
Yash
Above, the Shop
class has implemented the IEnumerable
interface that contains the GetEnumerator()
method.
This will enable the Shop
class to be used with the foreach loop that returns the Customer
objects.
- Difference between Array and ArrayList
- Difference between Hashtable and Dictionary
- How to write file using StreamWriter in C#?
- How to sort the generic SortedList in the descending order?
- Difference between delegates and events in C#
- How to read file using StreamReader in C#?
- How to calculate the code execution time in C#?
- Design Principle vs Design Pattern
- How to convert string to int in C#?
- Boxing and Unboxing in C#
- out keyword in C#
- Query geolocation & proxy data in .NET using IP2Location
- ref Keyword in C#
- How to sort an array in C#?
- How to sort object array by specific property in C#?
- How to get a comma separated string from an array in C#?
- How to remove duplicate values from an array in C#?
- How to combine two arrays without duplicate values in C#?
- Difference between String and string in C#.
- How to count elements in C# array?