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
exampleHow can we use a map collection in VB.NET? First we must create a new instance of the Dictionary
, with its generic type syntax.
Dictionary
after creating it.Dictionary
, we can loop over its keys and values with a For-Each
loop.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
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.
Select
Function.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.