Getting Started with C# Foreach Loop
Iteration statements are integral part of any programming language and are considered basic building block of a programming language. From the earliest of the programming languages, iteration statements have been used to implement logic that needs to be repeated in some way or the other. Historically there have been four iteration statements in most of the programming languages: The ‘for’, ‘while’, ‘do’ and ‘foreach’ loops. Every loop has a different function and some common functionality can be achieved via different loops. The ‘foreach’ loop is often times most efficient of its counterparts due to several advantages.
Want to know more about C# loops? Take this course
What is C# foreach Loop?
Before implementing C# foreach loops, following are some of the important points that must be kept in mind:
- Foreach loops in C# can be used only to iterate over those collections of items which implement IEnumerable interface from System.Collections namespace or IEnumerable<T> interface from System.Collections.Generic namespace. For example, simple arrays, strings, List collections, Dictionary collections etc. (To learn more about C# collections, take this course)
- Foreach loop is only used to enumerate the items of the collections. It cannot be used to add, insert, remove or update the items of a collection which is being enumerated.
- Both ‘break’ and ‘continue’ statements can be used with a ‘foreach’ loop to break out of a loop and to skip the statements in the loop, respectively.
How a C# foreach Loop Works?
Unlike, ‘for’ loops, ‘foreach’ loop doesn’t require a lower limit, an increment statement and an upper limit to decide that how many times it should execute. ‘Foreach’ loop starts enumerating over a collection from the first index and keeps enumerating till no more elements are left in the collection. Keeping tracking of the lower and upper bound is the task of .NET framework. This is what makes the ‘foreach’ loop much more efficient as compared to a simple ‘for’ loop. The following example demonstrates that how a ‘foreach’ loop can be used to enumerate over items in an array:
int[] odds = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; foreach (int num in odds) { Console.WriteLine(num); }
In the above code snippet, there is an integer array which has been named ‘odds’. This array contains all the odd numbers from 1 to 20. ‘Foreach’ loop has been used to enumerate all the numbers in this array. It can be seen that how simple is it to enumerate via a ‘foreach’ loop.
A temporary variable (num in the above code) is required followed by the ‘in’ keyword and the name of the collection. Each time loop iterates, the corresponding item of the collection is stored in ‘num’ variable and can be accessed inside the body of the loop.
Using ‘break’ inside a C# foreach Loop
The ‘break’ statement can be used inside a ‘foreach’ to exit the loop at any time. For instance, in following code, if the item is greater than 10, remaining items in the collection will not be displayed on the screen and loop will exit:
int[] odds = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; foreach (int num in odds) { if (num > 10) break; Console.WriteLine(num); }
In the above code snippet, only odd numbers from 1 to 10 will be displayed and as soon as the ‘foreach’ statement enumerates over number 11 (greater than 10) the loop will execute and remaining odd numbers would not be displayed.
Using ‘continue’ inside C# foreach loop
Using ‘continue’ statement inside a ‘foreach’ loop skips the remaining statements in the loop body and starts the next iteration. For example, in order to skip displaying all the elements in the collection that are divisible by 3, following code snippet can be used:
int[] odds = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; foreach (int num in odds) { if ((num % 3) == 0) continue; Console.WriteLine(num); }
When the ‘foreach’ loop reaches a number which is divisible by 3, the control will be shifted to the next iteration via ‘continue’ statement. If the above code is compiled and executed, all the odd numbers from 1 to 20 would be displayed except 3 and 15 since they are divisible by three.
For more about C# jump statements, take this course
Using C# foreach loop to iterate over generic list
As aforementioned, any collection that implements IEnumerable or IEnumerable<T> interface can be enumerated via ‘foreach’ loop. The C# generic list (List<T>) implements the IEnumerable<T> interface; therefore it can be enumerated via ‘foreach’. The following example demonstrates this concept:
The List<T> holds a collection of Person objects where definition of person class is as follows:
class Person { public string name; public int age; public string gender; public Person(string name, int age, string gender) { this.name = name; this.age = age; this.gender = gender; } }
In the main method, the following code can be used to add four objects of Person class in personcoll list which is actually a generic list:
List<Person> personcoll = new List<Person> { }; Person p1 = new Person("James", 20, "Male"); Person p2 = new Person("Mark", 25, "Male"); Person p3 = new Person("Sandra", 22, "Female"); Person p4 = new Person("Mark", 23, "Male"); personcoll.Add(p1); personcoll.Add(p2); personcoll.Add(p3); personcoll.Add(p4);
The ‘foreach’ loop can be used to display the contents of all the Person objects in the ‘personcoll’ generic list collection. This can be done in the following way:
foreach(Person p in personcoll) { Console.WriteLine(p.name +" "+ p.age +" "+p.gender ); }
In the above code snippet, ‘p’ is the temporary variable and every time ‘foreach’ loop enumerates over the personcoll, the corresponding person object would be stored in this temporary variable. The content of the Person object can then be obtained and displayed via this ‘p’ variable.
Similarly, C# ‘foreach’ loops can be used with LINQ to SQL classes as well as LINQ to Entity Framework where it can be used to iterate over collections of database table objects.
Interested in knowing more about C#? Check this introductory course
Recommended Articles
Top courses in C# (programming language)
C# (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.