c sharp

C# For Each Loop

Mainly, the “for” loop has been designed to iterate several statements within it without actually paying attention to their type. There are situations when your “for” loop doesn’t work due to some problems. At that time, there is the  “foreach” loop in C# for our help which is said to be an alternative for the “for” loop. It is most probably designed to iterate the values of an array or collections within C# and perform different operations according to the statements. So, we have decided to try the “foreach” loop of C# in our article today. Have a new start of this guide by the formation of a new C# file in our system to try making some C# programs.

Example 1

Before showing the examples of “for each” loop, we will be taking a look at the simple “for” loop first. Thus, the program has been started with the C# “System” main library within the text editor of the Ubuntu 20.04 system. The public class “Test” has been started with the main() function implementation in it. Within the main() method, we are using the simple “for” loop started from iteration 0 and ended at less than 5 i.e., 4. On each iteration, the loop will be performing the “Console.WriteLine()” function to display the string “Hello” with the iteration number “I” on the console screen. The “for” loop, main() method, and class is completed here.

After saving this code, we have tried to compile it with the “mcs” C# compiler in Ubuntu. The compilation was successful as it created an “exe” file for the code. Now, we have to run this “exe” file on the shell with the runtime executor “mono” of C#. On running it, we have got a total of 5 results for the “for” loop execution on each iteration. The string “Hello” along with the iteration number is displayed on our screen.

Now, we will be trying the alternative of the “for” loop i.e., “for each” in the C# program to get the very same type of results as we got with the use of a simple “for” loop. So, we have been using the System library and created a new class “Test” having a main() function within it. The main() function has been started with the string array “A” initialization with the 5 string values. Now, we have been utilizing the “foreach” loop here to iterate the values of an array “A” using the “I” iterator. The “string” keyword is showing that the elements of a string array will be taken from the array and displayed as the element “I”. This loop has been using the Console.WriteLine() function to display the same string “Hello” along with the elements of an array using “I” as iteration value.  The program is now complete and ready for use.

Now, we have compiled the code with the C# “mcs” compiler and executed its “exe” file with the “mono” runtime as shown. The output is displaying the string “Hello” along with the particular value at the particular iteration number of an array. The difference between “for” and “foreach” is now clear. The “for” loop takes “I” as an iterator and displays the iteration index at the display. While the “foreach” takes the iteration number and displays the value of the particular index at the display.

Example 2

Let’s see how a “foreach” loop works on integer-type arrays. So, within the same code file, we have updated the few code lines as shown. Added an integer array “A” with some integer values in it. The “foreach” loop has been started using the element iterator “I” and used the “Console.Write()” function to display each value from the array. After this loop, we have added a line break using the “\n” in the Console.Write() function statement.

After compilation and execution of this updated code, we have got the integer array values displayed at the same line one after another.

This was quite simple and basic. Let’s perform some simple calculations in the program. So, we have updated the code and declared an integer “z” taking a value of “I” incremented by 2. The Console.WriteLine() function is used to display the element at index “I” and the calculated value of “z” for the particular iteration.

After running this code, we have got each particular value displayed along with the incremented value of “z” at the shell screen.

Example 3

Now, we will be taking a look at the use of the “foreach” loop on 2-dimensional arrays.  So, within the same code, a 2-dimensional integer array “A” of size 3*3 has been initialized. This array size means 3 rows and 3 columns in mathematics. Each row contains 3 different values. We are using the same format of the “foreach” loop here to iterate the 2-dimensional array “A” and display its elements on the shell via the “I” variable in the Console.Write() statement.

After this code execution, we have got all the elements of the 2-dimensional array displayed at the same line in a 2-dimensional format of arrays.

Example 4

Now, we will be taking a look at the dictionary data structure using the “foreach” loop in C#. For using a dictionary, we have to add the System.Collections.Generic header in the code. Starting the Test class, we have initialized a main() function in this C# code. After this, we have initialized a variable “A” of dictionary type using the “Dictionary” Collection. We have declared the data type “int” for dictionary keys and “string” for values. After this, we have initialized this dictionary with some of the key-pair values as shown. The “foreach” loop is here to iterate the key-pair values of dictionary “A” using the variable “I”. On each iteration, each key-pair value will be displayed via the Console.WriteLine() function of System library. For this, the variable iterator “I” is calling the built-in “key” and “pair” function of a dictionary to display.

After this dictionary program code execution, each element from the dictionary has been displayed in key-value format i.e.,  Key 1, value Ana and so on.

Example 5

The last example is utilized to find out the largest value among the array values using the “foreach” loop. The first index value of an array has been declared as the maximum value “m”. The foreach loop is here to iterate the values of the array and compare each value of the array with the maximum “m” within the “if” condition. If the value in array index “I” Is greater than the maximum value “m”, the value of “I” will be assigned to maximum “m” and the loop will continue until the end of an array. After the loop ends, we will get our maximum value from the array and displayed it on the shell via the Console.WriteLine() statement.

After executing this code, we have found the largest value “130” from array “A”.

Conclusion

This tutorial is efficiently describing the use of “loops” in programming and makes a clear comparison between the “for” and “foreach” loops in C# programming. We have discussed different examples of arrays to iterate the values and display them on the console i.e., on a single line and separate lines as well. Trying simple calculations,  the “foreach” loop examples have been demonstrated perfectly for 2-dimensional arrays and dictionaries as well.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.