Iterate Through Collections with Foreach

Updated: Apr 10, 2020

When writing software, there are multiple scenarios where you will need to run a code block several times. Websites continually ask for your password until you enter the right one. Video game villains attack you until your hit points reach zero. Movie tracking applications display all the titles in a movie collection.



Loops exist in C# to allow you the functionality of repeating a segment of code.


There are four loops you need to understand when writing applications in C#: foreach, for, while, and do…while. This post focuses solely on the foreach loop. Information on the additional loops exists in other posts.

Foreach Loop

One of the most straightforward loops to understand is the foreach loop. The primary purpose of this loop is to iterate through a collection, running the code block for each element. Foreach is to loop through any most collection types (e.g., Array, List, Dictionary). Special collections like the Stack or Queue will need to be converted to an array before you can loop through those collections.

The foreach loop will evaluate every element in the collection. It does not need to know any index values. Therefore, there is no concern about causing an “argument out of range” exception. Foreach uses enumeration to access each element in consecutive order.

Syntax

foreach(DataType AliasName in CollectionVariable)
{
     Code Statement(s);
}

The critical parts of the foreach loop are:

  • The “foreach” keyword

  • The data type of the elements in the collection

  • An alias for the element currently being evaluated

  • The “in” keyword

  • The name of the collection to iterate through

  • The curly braces { } that mark the code block to execute for each iteration

  • The code statements to execute


 List<string> friendList = new List<string>();
 
 foreach (string friend in friendList)
 {
      Console.WriteLine(friend);
 }

With this example, friendList is the collection we want to iterate through. Each element is a string, and we are using the alias “friend” to store the value with each iteration. The code between the braces will display out the value of the element. When this application runs, every friend in the list will be displayed, whether there is one element or three thousand.

If there are no elements in the list, the application does not crash; it just doesn’t run the code block between the braces.

Limitations

The foreach loop is simple to understand and implement, but there are some limitations with a foreach.

  • A foreach will only iterate through the collection in a forwards direction

  • You can not change the values in the collection while looping through the elements

  • A foreach does not track the index of the elements. You will have to write additional code to determine the index value of the current element.

Workarounds

Although the limitations exist for the foreach loop, there are a few ways to get around the last two.

You can not change the values of the collection while looping through the elements, but you can use the loop to populate another collection.


 List<string> friendList = new List<string>();
 friendList.Add("Presty");
 friendList.Add("Katie");
 friendList.Add("Kate");
 friendList.Add("Brian");
 
 List<DateTime> friendBirthdays = new List<DateTime>();
 
 foreach (string friend in friendList)
 {
      Console.WriteLine("When is " + friend + "'s birthday?");
      DateTime birthday = Convert.ToDateTime(Console.ReadLine());
      friendBirthdays.Add(birthday);
 }

This code will loop through each friend in friendList and ask the user to enter a birthday for that person. As long as they enter a valid date, it is stored in the friendBirthdays list.

You can use the next workaround to print out both pieces of information together. By creating an integer value that increments every time a loop occurs, you can track the index value of the list. Since a foreach always iterates forward, there is no danger of this causing an error.

The following code will display each friend with the birthday that was entered for them.


 int counter = 0;
 foreach (string friend in friendList)
 {
      Console.WriteLine(friend + " has a birthday on " 
         + friendBirthdays[counter]);
      counter = counter + 1;
 }

Nested Loops

There will be times where you need to execute a loop within a loop. This functionality can be accomplished with all loop types, including the foreach. Inside a foreach loop, you can iterate through another collection or even the same collection a second time. The following code shows what this would look like


 List<string> foods = new List<string>()
 { "cake","ice cream","soda" };
 
 int counter = 0;
 foreach (string friend in friendList)
 {
      Console.WriteLine();
       Console.WriteLine(friend + " has a birthday on "       
           + friendBirthdays[counter]);
       counter = counter + 1;
 
       foreach (string name in friendList)
       {
             Console.WriteLine(name + " is invited to the party");
       }
       
       Console.WriteLine("We wil have...");
       
       foreach (string food in foods)
       {
             Console.WriteLine(food);
       }
       
       Console.WriteLine();
 }

36 views0 comments

Recent Posts

See All