Recipe 8.14. Iterating Through Array Elements


You want to process all the elements of an array without the overhead of creating extra variables, and you'd like to minimize the scope of all working variables.


Sample code folder: Chapter 08\ForEachLoops

Use the For Each looping construct to process each element of an array.


The following code creates a simple string array of fruit names, then processes each string in the array inside a For Each loop:

 Dim result As New System.Text.StringBuilder Dim fruitArray( ) As String = { _    "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} For Each fruit As String In fruitArray    result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) 

The For Each line declares a temporary variable named fruit that exists only for the duration of the For Each loop. This ties the variable name closely to the processing going on locally and frees up resources as soon as that processing is completed. Also, there is no need to access the length of the array to control the looping because the loop implicitly processes all elements, no matter what the array's size is. (The standard For loop syntax requires a separate counting variable and access to the array's length.) Figure 8-14 shows the results displayed by the example code.

Figure 8-14. Processing arrays with For Each loops

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400 © 2008-2017.
If you may any questions please contact us: