C# Array foreach loop
In this chapter you will learn:
- Use for each loop to output elements in an array
- Use Foreach statement to loop through Rectangular Array
- for vs foreach for multi-dimensional array
Array foreach loop
The following code creates an array and then uses foreach loop to output its value.
using System;//from w w w. j a v a 2s . c o m
class MainClass
{
public static void Main()
{
string s = "A B C D E";
char[] separators = {' '};
string[] words = s.Split(separators);
foreach (object obj in words)
Console.WriteLine("Word: {0}", obj);
}
}
The code above generates the following result.
Foreach with Rectangular Array
The following code shows the way of foreach loop with rectanglar array.
using System;/* www . ja va 2 s . com*/
class MainClass
{
static void Main()
{
int[,] arr1 = { { 0, 1 }, { 2, 3 } };
foreach (int element in arr1)
{
Console.WriteLine ("Element: {0}", element);
}
}
}
The code above generates the following result.
for vs foreach for multi-dimensional array
From the following code we can see that the foreach loop simplifies the iteratoration of multi-dimensional array.
using System; // w w w . j a v a 2 s.c o m
class MainClass {
public static void Main() {
int sum = 0;
int[,] nums = new int[3,5];
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i,j] = (i+1)*(j+1);
foreach(int x in nums) {
Console.WriteLine("Value is: " + x);
sum += x;
}
Console.WriteLine("Summation: " + sum);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Array.ForEach with a delegate
- Example for Array ForEach Action
- ForEach with your own delegate
- Use an Action to change the values