How to Use ForEach with Arrays in C# (C Sharp)

When you think about iteration statements in any language you use, the first iteration statement that strikes your mind will be for loop. In for loop you can iterate over an array or any collection one after the other and manipulate on each of the array elements. Here is a simple example:

class sampleClass {
public static void Main(){
string[] flowers = {“Jasmine”,”Rose”,”Lily”, “Lotus”};
Console.WriteLine(“Flowers Available Are:”);
for (int index=0; index< flowers.Length; index++) {
Console.Write (flowers[index] + “ “);
}
}
}

Output of this code will be:

Flowers Available Are Jasmine Rose Lily Lotus

In addition to for statement, C# provides similar iteration statement called foreach. Foreach statements are also used to iterate over elements of an array or collection. One significant difference between for and foreach statement is that: you cannot modify data inside a collection using foreach statement. You can only read and display the elements. However you can manipulate and alter data of a collection using for statement. Above example can be modified to use foreach statement as:

class sampleClass {
public static void Main(){
string[] flowers = {“Jasmine”,”Rose”,”Lily”, “Lotus”};
Console.WriteLine(“Flowers Available Are:”);
foreach (string flower in flowers) {
Console.Write (flower + “ “);
}
}
}

Output of this code will be:

Flowers Available Are Jasmine Rose Lily Lotus

Syntactical difference is clearly evident in the two version of codes mentioned above. You cannot specify a condition in foreach statement and incrementing the index will happen automatically. Inside foreach you don’t specify an integer index for iterating. Instead you directly assign the value of each element in the collection to the variable specified inside foreach.

In this example, each element of flowers array will be assigned to the string flower one at a time per iteration. In for statement you have an option to increment or decrement the iteration to any number. But in foreach, you cannot specify it as part of foreach statement but you can implement the incremental/decremental logic inside the code block. Even though foreach statement is used with both arrays and collections, the scope of this article is confined to the usage of foreach with arrays.

Unless you disturb the normal flow of execution, foreach statement will iterate over each element of the array. However you can perturb this normal flow of execution using the following keywords:

• break
• continue

Using foreach with break:

Using break keyword you can abruptly come out of the foreach statement without proceeding with rest of the code block inside foreach and rest of the iterations. For example, if you want to display only the first two elements of flowers array, you can modify the above mentioned example as shown below:

class sampleClass {
public static void Main(){
string[] flowers = {“Jasmine”,”Rose”,”Lily”, “Lotus”};
Console.WriteLine(“Flowers Available Are:”);
int index=0;
foreach (string flower in flowers) {
index++ ;
Console.Write (flower + “ “);
if(index == 2) {
break;
}
}
}
}

Output of this code will be:

Flowers Available Are Jasmine Rose

Using foreach with continue:

The continue keyword can be used along with foreach statement to skip the current iteration and continue with the next iteration of the array. If you want to display all the flowers except Rose, then you can modify the foreach statement as:

foreach (string flower in flowers) {
if (flower == “Rose”) {
continue;
}
Console.Write (flower + “ “);
}

Output of this code will be:

Flowers Available Are Jasmine Lily Lotus

When the flower is Rose, continue keyword is triggered and rest of the statements in foreach statement is skipped. Next iteration of flowers array will then happen.

Apart from these keywords, there are three other statements which can also disturb the flow of execution. They are goto, throw and return statements.

Using foreach with multidimensional arrays:

In the example discussed above, you have used foreach statement with a single dimensional string array. You can also use foreach statement with multidimensional arrays. In the following example, you iterate oven a three dimensional array using foreach statement:

class sampleClass {
public static void Main(){
string[, ] multiDimArr = new string[2, 2] { {“Lily”,”Lotus”}, { “Jasmine”,”Rose} };
foreach (string arrayElement in multiDimArr) {
System.Console.Write(arrayElement + “ “);
}
Output of this code will be:

Lily Lotus Jasmine Rose

Does it look strange? You are accessing multidimensional array in the same way as you access single dimensional array. You fetch each element in arrayElement irrespective of which dimension it belongs to. The best way to deal with multidimensional array is to use for loop which can be nested to n-level where n refers to the dimension. Using nested for loop you can fetch data in an orderly way and manipulate it as required.

| How does Yield Keyword of C# Use Lazy Evaluationm: Reference Types |How to Create Iterator to Process Generic List in C# | How to Use “add” and “remove” Contextual Keywords of C# | How to Use ForEach with Arrays in C# |Illustration of Operator Keywords (as, is) with Examples in C# | Illustration of Operator Keywords (new, sizeof) with Examples in C# |Illustration of Operator Keyword stackalloc with Examples in C# |Illustration of Operator Keywords (true, false) with Examples in C#|Illustration of Operator Keyword typeof with Examples in C# |List of Contextual Keywords in C#|


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.