vbnet
  1. vbnet-for-each-loop

Control Statements in VB.NET For Each Loop

The For Each loop is a control statement in VB.NET that allows you to iterate through the elements of a collection or an array. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of the For Each loop in VB.NET.

Syntax

Here is the syntax for the For Each loop in VB.NET:

For Each element In collection
    ' Statements to be executed
Next [element]

The element variable represents the current element of the collection, and collection is the collection or array that you want to iterate through. The Next keyword signals the end of the loop.

Optionally, you can include an Exit For statement inside the loop to exit the loop early.

Example

Here is an example of using the For Each loop in VB.NET:

Dim grades() As Integer = {90, 85, 75, 95, 80}

For Each grade As Integer In grades
    Console.WriteLine("Grade: " & grade)
Next

In this example, we are iterating through an array of grades and printing each grade to the console.

Output

The output of the example above will be:

Grade: 90
Grade: 85
Grade: 75
Grade: 95
Grade: 80

Explanation

The For Each loop in VB.NET is commonly used to iterate through collections and arrays. In the example above, we declared an array of integers called grades. We then used the For Each loop to iterate through each element of the array and print it to the console.

Use

The For Each loop in VB.NET is particularly useful when you need to perform an operation on each element of a collection or an array. It can save you the hassle of manually iterating through the elements of the collection or array.

Important Points

  • The For Each loop is a control statement in VB.NET that allows you to iterate through the elements of a collection or an array.
  • The loop variable element represents the current element of the collection, and collection is the collection or array that you want to iterate through.
  • The Next keyword signals the end of the loop.
  • Optionally, you can include an Exit For statement inside the loop to exit the loop early.

Summary

In this page, we discussed the syntax, example, output, explanation, use, important points, and summary of the For Each loop in VB.NET. The For Each loop is a versatile control statement that can be used to easily iterate through the elements of an array or a collection.

Published on: