The foreach statement repeats an embedded statement group for each element in an array or an object set. The foreach statement is used to cyclically access the set to obtain the required information, but should not be used to change the set content to avoid unpredictable side effects.
Remarks
--------------------------------------------------------------------------------
The embedded statement continues to be executed as an array or each element in the set. After completing Iteration for all elements in the Set, control the next statement passed to 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 directly enter the next iteration of the loop.
The foreach loop can also exit through the goto, return, or throw statements.
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 this example is:
9 99 3 33 5 55
However, for multi-dimensional arrays, nested for loops can better control 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 ());
It is obvious that the foreach statement is concise, but it is not only advantageous, but also has the highest efficiency. Many may think that the last one is more efficient, because on the surface, you don't need to access the attribute of the reference type each time. However, it is the most efficient among the three. Because c # is a strongly typed check, you need to judge the index's valid value when accessing the array. the actual effect of the last code is the same as that of 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 ();
}
1 2 3