Convert Dictionary to ListConvert a Dictionary to a List. Use the ToList Function and the KeyValuePair type.
This page was last reviewed on Mar 26, 2022.
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. With a sample program, we demonstrate this conversion in the VB.NET language.
Convert List, Array
Example. Let's create a Dictionary instance and set four different keys equal to four different values. Next, the ToList extension method can be used.
Then We can loop over each KeyValuePair in the List instance with a For-Each loop construct.
For Each, For
Module Module1 Sub Main() ' 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 ' Call ToList on it. ' ... Use KeyValuePair list. Dim list As List(Of KeyValuePair(Of String, Integer)) = dict.ToList ' 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 Module
cat 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 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 Mar 26, 2022 (rewrite).
© 2007-2023 Sam Allen.