Home
VB.NET
Loop Over String Array
Updated Nov 28, 2023
Dot Net Perls
Loop, String array. Suppose 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.
Example. 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.
Step 1 We use the For Each loop over the "array1" elements. We use string interpolation syntax to print each element to the console.
For
Step 2 We loop over the indexes of the array with a For-loop. We go to the Length minus 1, so avoid reading past the end.
Step 3 We can also use For To loops to iterate backwards—we must specify a Step of -1.
Step 4 Here is a functional version of For Each—we call a Sub on each element in the array with Array.ForEach.
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 Module
FOR 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 28, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen