How to use FOR EACH loop in VB.NET

When confronted with programming scenarios that require repetitive execution of a task multiple times or until a specific condition is met, loop statements prove invaluable in achieving the desired outcomes.

In Visual Basic.NET (VB.NET), the commonly employed loop statements include the FOR NEXT Loop, FOR EACH Loop, WHILE Loop, and DO WHILE Loop. These loop structures offer programmers versatile options to efficiently repeat code blocks and iterate through collections or perform iterative operations based on specified conditions in their VB.NET applications.

For Each Loop

The FOR EACH Loop is commonly utilized when there is a need to iterate over each individual element or item within a collection or group, such as elements in an Array, files in a folder, or characters in a String. This loop construct allows for seamless traversal through the entire collection, enabling the execution of specific actions on each element.

By employing the FOR EACH Loop, developers can efficiently process and manipulate each item within the group without the need for manual indexing or tracking of iteration variables. This loop structure greatly simplifies the code and enhances readability when working with collections in VB.NET.

For Each [Item] In [Group] [loopBody] Next [Item]
  1. Item : The Item in the group.
  2. Group : The group containing items.
  3. LoopBody : The code you want to execute within For Each Loop.

Let's consider a real-time example where you want to display each character in a website name, such as "https://net-INFORMATIONS.COM". In such a situation, employing the FOR EACH Loop proves highly convenient. By utilizing this loop structure, you can iterate through each character in the website name and perform specific operations or display them individually.

1. siteName = "https://net-INFORMATIONS.COM" 2. For Each singleChar In siteName 3. MsgBox(singleChar) 4. Next
  1. Line 1: Assigning the site name in a variable.
  2. Line 2: This line is extracting the single item from the group.
  3. Line 3: Loop body.
  4. Line 4: Taking the next step.

The FOR EACH Loop allows you to effortlessly access and process each character without the need for manual indexing or manipulating string positions. This approach enhances code clarity and simplifies the task of working with individual elements in a string.

Full Source VB.NET
Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim siteName As String Dim singleChar As Char siteName = "https://net-INFORMATIONS.COM" For Each singleChar In siteName MsgBox(singleChar) Next End Sub End Class

When you execute this program you will get each character of the string in Messagebox.