
You want to use the ToDictionary method in your VB.NET program to quickly construct a dictionary from a collection such an array. With ToDictionary, you provide two functions that indicate how the key and value are created from each element.
This VB tutorial shows how to use the ToDictionary extension from System.Linq.

To start, this program creates an array of String elements with four String literals. Next, we invoke the ToDictionary extension method. ToDictionary has two arguments: these are functions specified as lambda expressions. They both receive one argument: the String from the source array. They return a String (for the first, key selector function) and an Integer (for the value selector function).
Program that uses ToDictionary method [C#]
Module Module1
Sub Main()
' Create an array of four string literal elements.
Dim array() As String = {"dog", "cat", "rat", "mouse"}
' Use ToDictionary.
' ... Use each string as the key.
' ... Use each string length as the value.
Dim dict As Dictionary(Of String, Integer) = array.ToDictionary(Function(value As String)
Return value
End Function,
Function(value As String)
Return value.Length
End Function)
' Display dictionary.
For Each pair In dict
Console.WriteLine(pair)
Next
End Sub
End Module
Output
[dog, 3]
[cat, 3]
[rat, 3]
[mouse, 5]
More details. You can see that the two parameters to ToDictionary both receive the same parameter, but return different values. The first Function tells how the String is transformed into a key; we simply use the original String as the key without any mutation. The second Function tells how the String is transformed into a value; we return the string's length as the value.
Results. The resulting Dictionary(Of String, Integer) has String keys and Integer values. The value in each pair is equal to the length of the String key.
We used lambda expressions in the VB.NET language syntax to call the ToDictionary extension method. We provided a way for each string element to be transformed into a KeyValuePair in the resulting Dictionary(Of String, Integer) collection. In this way, you can use ToDictionary to quickly construct Dictionary instances to improve the performance of future lookups.
Dictionary Examples VB.NET Tutorials