Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

Foreach Loop in CSharp

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
string[] carCompanies = { "Tata Motors", "Mahindra", "Volkswagen", "Toyota" };
																
foreach(string car in carCompanies)
{
	Console.WriteLine("{0}", car);
}
Try it
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 =&gt; Console.Write(num)); //using ForEach extension method
Try it
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 the IEnumerable 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.

Example: Iterate a Dictionary
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);
}
Try it
Output:
UK, London, Manchester, Birmingham
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.

Example: Implement IEnumerable Interface
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);
		}
	}
}
Try it
Output:
Steve
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.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.