Map. A map is a collection that has keys, and values for each key. And the term may refer to a function that applies a method to each element in a collection.
In VB.NET, the term "map" does not have a specific meaning, so we must use the Dictionary type and Select function. A lambda expression can be used as an argument to Select.
Collection example. How can we use a map collection in VB.NET? First we must create a new instance of the Dictionary, with its generic type syntax.
Part 1 We add 2 keys, with associated values, to the Dictionary after creating it.
Part 2 When using a Dictionary, we can loop over its keys and values with a For-Each loop.
Part 3 It is possible to access the map at a key, but this will throw an exception if the key is not found.
Part 4 With TryGetValue, we can access a value at a key more safely—if the key is not found, no exception is thrown (False is returned instead).
Module Module1
Sub Main()
' Part 1: create new Dictionary and add 2 keys and values.
Dim map = New Dictionary(Of String, String)()
map.Add("cat", "orange")
map.Add("dog", "brown")
' Part 2: loop over the map.
For Each pair In map
Dim key = pair.Key
Dim value = pair.Value
Console.WriteLine($"{key} / {value}")
Next
' Part 3: access value at key.
Dim result = map("cat")
Console.WriteLine(result)
' Part 4: access value at key with TryGetValue (safer).
Dim result2 = Nothing
If map.TryGetValue("dog", result2)
Console.WriteLine(result2)
End If
End Sub
End Modulecat / orange
dog / brown
orange
brown
Modify array. Another use of the term "map" means to apply a function each element of a collection (like an array). This can be done with the Select function in VB.NET.
Tip We pass a lambda expression with the Function keyword as an argument to the Select Function.
Tip 2 In languages like Python, the "map" function is equivalent to Select() in VB.NET.
Module Module1
Sub Main()
Dim array As String() = { "bird", "fish" }
' Print original array.
Console.WriteLine(String.Join(",", array))
' Call a Function on each element in the array, modifying the element.
Dim result = array.Select(Function (x)
Return x.ToUpper()
End Function).ToArray()
' Print result.
Console.WriteLine(String.Join(",", result))
End Sub
End Modulebird,fish
BIRD,FISH
VB.NET programs can create map collections with a Dictionary, and map elements in collections with the Select function. Mapping things is an essential task in this language.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.