We introduce the MultiMap class, which contains a Dictionary field. We then have the Add Function, a Keys property, and an indexer (a This property).
Class MultiMap
Dim _dictionary as Dictionary(Of String, List(Of String)) = New Dictionary(Of String, List(Of String))
Public Sub Add(key As String, value As String)
' Add a String key.
' For the list of values, add a value onto the end of the List if one exists.
Dim list as List(Of String) = Nothing
If _dictionary.TryGetValue(key, list)
list.Add(value)
Else
list = New List(Of String)
list.Add(value)
_dictionary(key) = list
End If
End Sub
Public ReadOnly Property Keys As IEnumerable(Of String)
Get
' Get all keys.
Return _dictionary.Keys
End Get
End Property
Public ReadOnly Default Property This(key As String) As List(Of String)
Get
' Get list at a key.
Dim list As List(Of String) = Nothing
' Create empty list if none exists.
If Not _dictionary.TryGetValue(key, list)
list = New List(Of String)
_dictionary(key) = list
End If
Return list
End Get
End Property
End Class
Module Module1
Sub Main()
' Part 1: Create MultiMap by calling Add Function.
Dim multiMap = New MultiMap()
multiMap.Add(
"animal",
"cat")
multiMap.Add(
"animal",
"dog")
multiMap.Add(
"color",
"blue")
multiMap.Add(
"color",
"orange")
multiMap.Add(
"mineral",
"calcium")
' Part 2: Loop over keys in MultiMap with property.
For Each key in multiMap.Keys
' Part 3: Access all values for a specific key, and print them.
For Each value in multiMap(key)
Console.WriteLine($
"MULTIMAP: {key} = {value}")
Next
Next
End Sub
End Module
MULTIMAP: animal = cat
MULTIMAP: animal = dog
MULTIMAP: color = blue
MULTIMAP: color = orange
MULTIMAP: mineral = calcium