Convert Dictionary, List. A VB.NET Dictionary can be converted to a List. It can be represented as a List of KeyValuePairs. The ToList Function is useful here.
In converting Dictionaries and Lists, we have to understand that we may need to have KeyValuePairs. We demonstrate this conversion in the VB.NET language.
Example. We are acting on a Dictionary of String keys and Integer values, but these types can be changed. The Dictionary is a generic type, so it can be used with many key and value types.
Module Module1
Sub Main()
' Step 1: create example dictionary.
Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
dict("cat") = 1
dict("dog") = 2
dict("mouse") = 3
dict("palomino") = 4
' Step 2: call ToList on it (use KeyValuePair list).
Dim list As List(Of KeyValuePair(Of String, Integer)) = dict.ToList
' Step 3: we can loop over each KeyValuePair.
For Each pair As KeyValuePair(Of String, Integer) In list
Console.WriteLine(pair.Key)
Console.Write(" ")
Console.WriteLine(pair.Value)
Next
End Sub
End Modulecat
1
dog
2
mouse
3
palomino
4
Discussion. Why would a programmer want to convert a Dictionary into a List? Looping over every element in a List is much faster than looping over all the pairs in a Dictionary.
And Lists will use less memory because no internal buckets array is necessary.
However On the other hand, Dictionary provides faster lookup and element removal.
Thus In most performance-sensitive programs that do key lookups, Dictionary is a better choice.
A summary. Here we converted a Dictionary into a List. A List of KeyValuePairs can always represent the data inside a Dictionary. The main difference between is performance.
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.
This page was last updated on Apr 21, 2023 (simplify).