4.3 Enumerating Arrays with the foreach Operator

 <  Day Day Up  >  

4.3 Enumerating Arrays with the foreach Operator

You want to access all the elements within an array without requiring the use of index values.


Technique

To enumerate an array, use the foreach iteration statement, specifying the data type of an individual element within the array, the variable name for the element returned as a result of the enumeration, and the in keyword and variable name of the array:

 
 static void TestSingleDimensionArray() {     int[] arr1 = {1,2,3,4,5,6,7,8,9,10};     foreach( int elem in arr1 )     {         Console.WriteLine( elem );     } } 

Comments

In the previous recipes' code listings, the contents of each array were enumerated using for loops . For single-dimension arrays, the format was simple. However, as soon as you begin adding extra dimensions in the array, using for loops starts to seem less attractive. To enumerate a multidimension array using for loops, you have to create a for loop for each dimension that is nested within the for loop preceding it. For an array with even a small number of dimensions, this process can get quite tedious .

Luckily, the C# language has a built-in enumeration keyword designed for this specific purpose. foreach allows you to easily access every single item within a collection in a linear fashion. You can therefore replace each for loop for a multi-dimension array with a single foreach statement. However, when you do so, you are losing the benefit of knowing exactly which index is being accessed within the loop because you no longer use index variables to access each individual element. For a single-dimension array, you can simply create an integer variable and increment it each time within the body of the foreach statement, but for multidimension arrays, this step is not possible without using an algorithm to figure out the index of the current element being accessed within the foreach loop. The next recipe shows one possible solution.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net