Range Over Built in Visual Basic .NET
On this page
Here is the translation of the provided code example to Visual Basic .NET along with the necessary Markdown explanation:
Range over Built-in Types
Range iterates over elements in a variety of built-in data structures. Let’s see how to use For Each with some of the data structures we’ve already learned.
Here we use For Each to sum the numbers in an array. Arrays work like this too.
Imports System
Module Program
Sub Main()
Dim nums As Integer() = {2, 3, 4}
Dim sum As Integer = 0
For Each num As Integer In nums
sum += num
Next
Console.WriteLine("sum: " & sum)
End Sub
End ModuleFor Each on arrays and collections provides both the index and value for each entry. In the above example, we didn’t need the index, so we ignored it. Sometimes we actually want the indexes though.
Imports System
Module Program
Sub Main()
Dim nums As Integer() = {2, 3, 4}
For i As Integer = 0 To nums.Length - 1
If nums(i) = 3 Then
Console.WriteLine("index: " & i)
End If
Next
End Sub
End ModuleFor Each on dictionary iterates over key/value pairs.
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim kvs As New Dictionary(Of String, String) From {
{"a", "apple"},
{"b", "banana"}
}
For Each kvp As KeyValuePair(Of String, String) In kvs
Console.WriteLine(kvp.Key & " -> " & kvp.Value)
Next
End Sub
End ModuleFor Each can also iterate over just the keys of a dictionary.
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
Dim kvs As New Dictionary(Of String, String) From {
{"a", "apple"},
{"b", "banana"}
}
For Each key As String In kvs.Keys
Console.WriteLine("key: " & key)
Next
End Sub
End ModuleFor Each on strings iterates over Unicode code points. The first value is the character itself. See Strings and Runes for more details.
Imports System
Module Program
Sub Main()
Dim str As String = "go"
For Each c As Char In str
Console.WriteLine(c)
Next
End Sub
End ModuleTo run the programs, compile the VB.NET code using vbc and execute it.
$ vbc Program.vb
$ Program.exeNext example: Pointers.