The foreach statement repeats an embedded statement group for each element in an array or collection of objects. The foreach statement is used to iterate through the collection to obtain the required information, but it should not be used to change the contents of the collection to avoid unpredictable side effects.
Note
--------------------------------------------------------------------------------
An embedded statement continues execution for each element in an array or collection. When the iteration is completed for all elements in the collection, control is passed to the next statement after the foreach block.
You can use the break keyword to jump out of the loop at any point in the foreach block, or use the Continue keyword to go directly to the next iteration of the loop.
The Foreach loop can also be exited by a Goto, return, or throw statement.
int[,] numbers2d = new int[3, 2] {9, 99}, {3, 33}, {5, 55}};
foreach (int i in numbers2d)
{
System.console.write ("{0}", i);
}
The output of the example is:
9 99 3 33 5 55
For multidimensional arrays, however, you can use nested for loops to better control the array elements.
int[] Narray = new int[100];
Use ' foreach ' to loop array
foreach (int i in Narray)
Debug.WriteLine (i.ToString ());
Use ' for ' to loop array
for (int i = 0; i < narray.length; i++)
Debug.WriteLine (Narray[i].tostring ());
Another way using ' for ' to loop array
int nlength = Narray.length;
for (int i = 0; i < nlength; i++)
Debug.WriteLine (Narray[i].tostring ());
Obviously, the foreach statement is concise, but its advantages are not only this, it is also the highest efficiency. Many people may think that the last one will be more efficient because it looks as if it doesn't have to access the properties of the reference type each time. But it is among the three, the lowest efficiency. Because C # is a strong type check, for array access, the effective value of the index is judged, so the last code actually produces the same effect as the following code.
Another way using ' for ' to loop array
int nlength = Narray.length;
for (int i = 0; i < nlength; i++)
{
if (I < narray.length)
Debug.WriteLine (Narray[i].tostring ());
Else
throw new IndexOutOfRangeException ();
}