Recommended Books

VB.NET For each loop



This Article covers the VB.NET For Each loop.

The For Each Loop is a special variant of the VB.NET For Loop designed to be used to iterate over iterables such as Arrays. Iterating allows us to individually access and manipulate each element in the iterable.

For explanation purposes, we’ll show a very simple use of the For Each Loop.

The following code will iterate over each element in the Array and print it out individually. Useful if you don’t want it in an Array format, or just want a single element printed (You can achieve this with an If statement!).

Module Module1
    Sub Main()

        Dim Arr() As Integer = {1, 2, 3, 4, 5}
        Dim element As Integer

        For Each element In Arr
            Console.WriteLine(element)
        Next
        Console.ReadLine()

    End Sub
End Module

Here is the output, one element per line.

1
2
3
4
5

Example

Here we’ll show a common usage of the For Each loop.

The code below will iterate over each element, and with each iteration the current element will be added in the a variable called sum. Finally, the variable sum is printed after the loop is over, and we get the sum of all elements.

Module Module1
    Sub Main()

        Dim Arr() As Integer = {1, 2, 3, 4, 5}
        Dim element As Integer
        Dim sum As Integer = 0

        For Each element In Arr
            Console.WriteLine(element)
            sum += element
        Next
        Console.WriteLine(sum)
        Console.ReadLine()

    End Sub
End Module

Almost the same as before, except for the additional output of the sum variable.

1
2
3
4
5
15

If you are ever faced with numbers in a string format (happens very commonly), as shown below, you can use the CInt() to convert it to an integer.

Dim Arr() As Integer = {"1", "2", "3", "4", "5"}

 For Each element In Arr
        Console.WriteLine(element)
        sum += CInt(element)
 Next

Vice Versa, you can use the CStr() to convert an integer or float into a string value.


This marks the end of the VB.NET For Each loop article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article can be asked in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *