Maps in Visual Basic .NET
Maps are Visual Basic .NET’s built-in associative data type (sometimes called hashes or dicts in other languages).
Imports System
Imports System.Collections.Generic
Module Program
Sub Main()
' To create an empty map, use the New keyword
Dim m As New Dictionary(Of String, Integer)()
' Set key/value pairs using typical name(key) = val syntax.
m("k1") = 7
m("k2") = 13
' Printing a map with Console.WriteLine will show all of
' its key/value pairs.
Console.WriteLine("map: {0}", String.Join(", ", m))
' Get a value for a key with name(key).
Dim v1 As Integer = m("k1")
Console.WriteLine("v1: {0}", v1)
' If the key doesn't exist, an exception is thrown.
' You can use TryGetValue to safely get a value.
Dim v3 As Integer
If m.TryGetValue("k3", v3) Then
Console.WriteLine("v3: {0}", v3)
Else
Console.WriteLine("v3: Key not found")
End If
' The Count property returns the number of key/value
' pairs in a Dictionary.
Console.WriteLine("len: {0}", m.Count)
' The Remove method removes key/value pairs from
' a Dictionary.
m.Remove("k2")
Console.WriteLine("map: {0}", String.Join(", ", m))
' To remove all key/value pairs from a Dictionary, use
' the Clear method.
m.Clear()
Console.WriteLine("map: {0}", String.Join(", ", m))
' The ContainsKey method can be used to check if a key
' exists in the Dictionary.
Dim prs As Boolean = m.ContainsKey("k2")
Console.WriteLine("prs: {0}", prs)
' You can also declare and initialize a new Dictionary in
' the same line with this syntax.
Dim n As New Dictionary(Of String, Integer) From {
{"foo", 1},
{"bar", 2}
}
Console.WriteLine("map: {0}", String.Join(", ", n))
' Visual Basic .NET doesn't have a built-in function to compare
' Dictionaries. You can create a custom function or use LINQ.
Dim n2 As New Dictionary(Of String, Integer) From {
{"foo", 1},
{"bar", 2}
}
If n.Count = n2.Count AndAlso Not n.Except(n2).Any() Then
Console.WriteLine("n == n2")
End If
End Sub
End Module
Note that Dictionaries appear in the form key=value, key=value
when printed with String.Join
.
To run the program, save it as Maps.vb
and use the Visual Basic .NET compiler:
$ vbc Maps.vb
$ mono Maps.exe
map: k1=7, k2=13
v1: 7
v3: Key not found
len: 2
map: k1=7
map:
prs: False
map: foo=1, bar=2
n == n2
In Visual Basic .NET, we use the Dictionary(Of TKey, TValue)
class to represent maps. This class provides similar functionality to Go’s maps, but with some differences in syntax and behavior. For example, accessing a non-existent key throws an exception in VB.NET, whereas in Go it returns a zero value. We’ve adapted the code to handle these differences while maintaining the overall structure and purpose of the original example.