VB.NET Convert Dictionary to List

Conversion or change

How can you convert your Dictionary instance to a List format in your VB.NET program? Any Dictionary can be represented instead as a List of KeyValuePairs. With this sample program, we demonstrate this conversion in the VB.NET language.

This VB program converts a Dictionary to a List. It uses ToList.

Example

Let's get started by creating a Dictionary instance and setting four different keys equal to four different values. Next, the ToList extension method can be used. Please note this method is not available in older versions of the .NET Framework. Finally, we can loop over each KeyValuePair in the List instance.

Program that converts Dictionary to List [VB.NET]

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 now.
	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

Output

cat
  1
dog
  2
mouse
  3
palomino
  4
Question and answer

Why? What are some of the motivations to convert a Dictionary into a List? First, looping over every element in a List is much faster than looping over all the pairs in a Dictionary. Second, Lists will use less memory because no buckets array is necessary.

List Tips

On the other hand, the Dictionary will provide much faster lookup times and faster element removal times. In most performance sensitive programs, the Dictionary is overall a better choice. Sometimes, you can use parallel collections and use the one which is most efficient as needed.

Dictionary Examples

Summary

The VB.NET programming language

Here, we converted a Dictionary instance into a List instance. A List of KeyValuePairs can always represent the data inside a Dictionary. The main difference between these two representations is in the areas of performance and the naming of their methods.

VB.NET Tutorials
.NET