String
arraySuppose you have a String
array in your VB.NET program, and want to loop over its elements. This can be done in various ways in this language.
A For Each
loop is the clearest and least error-prone, but other loops like For may be more useful in some programs. A For Step loop can be used to loop in reverse.
To begin, we need to have a String
array for our various loops. We use array initializer syntax to create a String
array of 4 elements.
For Each
loop over the "array1" elements. We use string
interpolation syntax to print each element to the console.For
-loop. We go to the Length
minus 1, so avoid reading past the end.For Each
—we call a Sub
on each element in the array with Array.ForEach
.Module Module1 Sub Main(args as String()) Dim array1() As String = {"one", "two", "three", "four"} ' Step 1: loop over the array with For Each. For Each value in array1 Console.WriteLine($"FOR EACH: {value}") Next ' Step 2: loop over the array with For. For i = 0 To array1.Length - 1 Dim value as String = array1(i) Console.WriteLine($"FOR: {value}") Next ' Step 3: loop over the string array backwards. For i = array1.Length - 1 To 0 Step -1 Dim value = array1(i) Console.WriteLine($"BACKWARDS: {value}") Next ' Step 4: loop with Array.ForEach subroutine with a lambda. Array.ForEach(array1, Sub(value As String) Console.WriteLine($"ForEach: {value}") End Sub) End Sub End ModuleFOR EACH: one FOR EACH: two FOR EACH: three FOR EACH: four FOR: one FOR: two FOR: three FOR: four BACKWARDS: four BACKWARDS: three BACKWARDS: two BACKWARDS: one ForEach: one ForEach: two ForEach: three ForEach: four
String
arrays, like other arrays in VB.NET, can be looped over in several ways. We can use For loops, or even the Array.ForEach
subroutine to call a subroutine repeatedly.