For each Loop

One way to loop over the elements in an array using visual basic is to use For each loop. Because it automatically loops over all elements in the array or collections. And it works well when you can associate each iteration of a loop with a control variable and determine that variable’s initial and final values. And you don’t have to worry about getting the indices in order to get all the elements. For Each Loop Syntax
For Each element [ As datatype ] In group
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ element ]
The For Each loop is always the best choice when you are dealing with every single element or an item in a group. For example, your looping every single file in a folder or any character in a string. This time, let’s Open visual basic and Create a New Project then save it as “Foreach”. Then, add a button on the windows form and change the Text property to “Go”. Next, we’re going to add functionality to an application. To do this double click the button and add the following code:
  1. 'declare array as a string with six index
  2. Dim letter(6) As String
  3. 'here, we assign values to specific index of an array
  4. letter(0) = "A"
  5. letter(1) = "B"
  6. letter(2) = "C"
  7. letter(3) = "D"
  8. letter(4) = "E"
  9. letter(5) = "F"
  10. letter(6) = "G"
  11.  
  12. ' Iterate through the list.
  13. For Each i As String In letter
  14. ' Display the letter
  15. MsgBox(i)
  16. Next 'Taking the Next step
Output: A B C D E F G We can also loop through the array and display the output in descending order like Z-A. Above the For each statement, add the following code:
  1. Array.Reverse(letter)
When completing, the code should look like as shown below.
  1. 'declare array as a string with six index
  2. Dim letter(6) As String
  3. 'here, we assign values to specific index of an array
  4. letter(0) = "A"
  5. letter(1) = "B"
  6. letter(2) = "C"
  7. letter(3) = "D"
  8. letter(4) = "E"
  9. letter(5) = "F"
  10. letter(6) = "G"
  11.  
  12. Array.Reverse(letter)
  13. ' Iterate through the list.
  14. For Each i As String In letter
  15. ' Display the letter
  16. MsgBox(i)
  17. Next 'Taking the Next step
You can now test you application by pressing “F5”.

Add new comment