Home
VB.NET
Map Example
This page was last reviewed on Feb 20, 2024.
Dot Net Perls
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.
Shows a mapShows a map
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.
Dictionary
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).
Shows a map
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 Module
cat / 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.
Lambda
Shows a map
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 Module
bird,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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 20, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.