For Each
Again and again, a VB.NET loop executes statements. The For
-loop proceeds from a lower to an upper bound—a step indicates its progression.
Another loop, For-Each
, requires a collection—it enumerates each item. Other loops, such as While, continue until a condition is met. If the end is not yet known, While is best.
To begin, we see a simple For
-loop that starts at 0, and continues to 2 (it includes 2, which is specified as the loop bound). In VB.NET the top bound is inclusive.
Module Module1 Sub Main() ' Simple example, loop from 0 to 2. For i As Integer = 0 To 2 Console.WriteLine("I: {0}", i) Next End Sub End ModuleI: 0 I: 1 I: 2
Consider a For
-loop that goes from 0 to (and including) 5. We can optionally place an Exit For inside this loop for added control over iteration.
For
-loop statement. The two bounds are inclusive (0 and 5 are included).For
-loop. Exit works in all loops and Subs.Module Module1 Sub Main() ' Step 1: specify a loop goes from 0 to 5. For value As Integer = 0 To 5 ' Step 2: print the current index of the loop. Console.WriteLine("CURRENT FOR-INDEX: {0}", value) ' Step 3: exit condition if the value is 3. If value = 3 Then Exit For End If Next End Sub End ModuleCURRENT FOR-INDEX: 0 CURRENT FOR-INDEX: 1 CURRENT FOR-INDEX: 2 CURRENT FOR-INDEX: 3
Here we want to decrement the counter variable instead of increment it. In other words, we go down not up. We start at 10 and then continued own in steps of 2 to 0.
For
-statement. A step is the delta each loop iteration will have.Module Module1 Sub Main() ' This loop uses Step to go down 2 each iteration. For value As Integer = 10 To 0 Step -2 Console.WriteLine(value) Next End Sub End Module10 8 6 4 2 0
In many programs, nested loops are essential. In a For
-loop, we uniquely name the iteration variable. And we reference all iteration variables (row, column) in an inner block.
Module Module1 Sub Main() ' Use a nested For-loop. For row As Integer = 0 To 2 For column As Integer = 0 To 2 Console.WriteLine("{0},{1}", row, column) Next Next End Sub End Module0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2
For Each
exampleNext, we consider the For-Each
loop construct. We create a String
array (of color names). We enumerate each string
in the array.
For-Each
, we reduce errors in programs. We do not need to maintain the index ourselves.Console.WriteLine
.Module Module1 Sub Main() ' The input array. Dim colors() As String = {"blue", "orange", "yellow", "magenta"} ' Loop over each element with For Each. For Each color As String In colors Console.WriteLine(color) Next End Sub End Moduleblue orange yellow magenta
For Each
, comparedHow does the For-Each
loop compare to the For
-loop? First, the For
-loop construct may be faster in some cases.
For
-loop has more complexity and is longer in the source code.Module Module1 Sub Main() ' The input array. Dim shapes() As String = {"circle", "square", "ellipse", "rectangle"} ' Loop over each element with For Each. For Each shape As String In shapes Console.WriteLine(shape) Next ' Blank line. Console.WriteLine() ' Use For-loop. For index As Integer = 0 To shapes.Length - 1 Console.WriteLine(shapes(index)) Next End Sub End Modulecircle square ellipse rectangle circle square ellipse rectangle
For Each
, List
Often we use For Each
on a List
. The loop works on anything that implements IEnumerable
, which includes Lists and arrays. Here we enumerate an Integer List
.
Module Module1 Sub Main() ' Create new List of 5 Integers. Dim ids = New List(Of Integer)({100, 101, 120, 121, 123}) ' Enumerate all IDs. For Each id In ids Console.WriteLine($"FOR EACH, CURRENT ID = {id}") Next End Sub End ModuleFOR EACH, CURRENT ID = 100 FOR EACH, CURRENT ID = 101 FOR EACH, CURRENT ID = 120 FOR EACH, CURRENT ID = 121 FOR EACH, CURRENT ID = 123
String
CharsThe For and For-Each
loops can be used on String
variables. This gives us a way to check, or process, each character in the Object data.
For-Each
loop can also be used on Strings. When you do not need the index, For-Each
is a better, cleaner choice.Module Module1 Sub Main() Dim value As String = "cat" ' Start at zero and proceed until final index. For i As Integer = 0 To value.Length - 1 ' Get character from string. Dim c As Char = value(i) ' Test and display character. If c = "c" Then Console.WriteLine("***C***") Else Console.WriteLine(c) End If Next End Sub End Module***C*** a t
Often in For
-loops, we need adjacent indexes. We can start at the second index (1) and then access the previous element each time, getting all pairs.
For
-loop, we could check for duplicates in a sorted array, or repeated values in any array.Module Module1 Sub Main() Dim value As String = "abcd" ' Start at one so the previous index is always valid. For i As Integer = 1 To value.Length - 1 ' Get adjacent characters. Dim c As Char = value(i - 1) Dim c2 As Char = value(i) Console.WriteLine(c & c2) Next End Sub End Moduleab bc cd
The For
-loop supports non-integer indexes like Long, Short
and UShort
. Char
is not supported. Here we use For with a Long index.
Module Module1 Sub Main() ' Loop over last three Longs. For d As Long = Long.MaxValue To Long.MaxValue - 2 Step -1 Console.WriteLine(d) Next End Sub End Module9223372036854775807 9223372036854775806 9223372036854775805
Let us revisit nested "For" loops with a more complex example. Here we have a loop that decrements inside a loop that increments.
For
-loop. Inside this loop, we have a nested loop.for
-loops are nested, and we have an Exit For statement, the inner loop is exited.Module Module1 Sub Main() ' Part 1: outer for-loop. For value As Integer = 0 To 3 Console.WriteLine("OUTER LOOP: {0}", value) ' Part 2: inner for-loop. For value2 As Integer = 5 To 0 Step -1 Console.WriteLine("INNER LOOP: {0}", value2) ' Part 3: exit condition. If value2 = 3 Then ' ... Exit the inner loop. Console.WriteLine("EXIT INNER FOR") Exit For End If Next Next End Sub End ModuleOUTER LOOP: 0 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 1 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 2 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 3 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR
The For
-loop is a core looping construct. It provides a way to explicitly specify the loop bounds. Meanwhile, For Each
helps us avoid coding errors by not using the index at all.