TheDeveloperBlog.com


C# Convert Dictionary to List

Convert dictionary, list. A Dictionary can be converted into a List. Specifically it is converted to a List of pairs. This requires the ToList extension method. ToList is part of the System.Linq extensions to the C# language.


Example. To start, we include the System.Collections.Generic and System.Linq namespaces. We create and populate a Dictionary collection. Next, we call ToList() on that Dictionary collection, yielding a List of KeyValuePair instances.

Then: We loop over the List instance, using a foreach-loop with the KeyValuePair iteration variable.

KeyValuePair

Finally: We print all the Key and Value properties with the Console.WriteLine method.

Console.WriteLine
C# program that calls ToList on Dictionary

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	Dictionary<string, int> dictionary = new Dictionary<string, int>();
	dictionary["cat"] = 1;
	dictionary["dog"] = 4;
	dictionary["mouse"] = 2;
	dictionary["rabbit"] = -1;

	// Call ToList.
	List<KeyValuePair<string, int>> list = dictionary.ToList();

	// Loop over list.
	foreach (KeyValuePair<string, int> pair in list)
	{
	    Console.WriteLine(pair.Key);
	    Console.WriteLine("   {0}", pair.Value);
	}
    }
}

Output

cat
   1
dog
   4
mouse
   2
rabbit
   -1

How does it work? The ToList extension method acts upon an IEnumerable generic collection. The Dictionary implements the IEnumerable interface with type parameter KeyValuePair<K, V>.

Thus: The Dictionary's implementation allows the ToList extension method to work here.

ToListIEnumerable Examples: LINQ, Lists and Arrays

Question—why would you ever want to convert your Dictionary to a List? First, there may be other methods in your program that require a List not a Dictionary. Second, the List has some superior performance characteristics.

List: It is faster to loop over and requires less memory due to its lack of an internal buckets structure.

Dictionary Versus List Lookup Time

Example 2. Here we populate a Dictionary with the values in a List. Look closely how you can use ContainsKey in the loop in which you add the elements to the Dictionary. This avoids the chance of an exception being raised.

ContainsKey
C# program that converts List

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Create new List. [1]
	List<string> list = new List<string>();
	list.Add("Olympics");
	list.Add("Nascar");
	list.Add("Super Bowl");
	list.Add("Wimbledon");

	// Put List values into Dictionary. [2]
	var exampleDictionary = new Dictionary<string, int>();
	foreach (string value in list)
	{
	    if (!exampleDictionary.ContainsKey(value))
	    {
		exampleDictionary.Add(value, 1);
	    }
	}

	// Display Dictionary. [3]
	foreach (var pair in exampleDictionary)
	{
	    Console.WriteLine(pair);
	}
    }
}

Output

[Olympics, 1]
[Nascar, 1]
[Super Bowl, 1]
[Wimbledon, 1]

Part 1. The first part of the example populates the List with four arbitrary string values. The List then has four elements. We need to add these four elements to the Dictionary next.

Part 2. Here we declare a new Dictionary that has a key type of string, which is the same type as the List. Having the types match is important. We loop through the List. We only call Add if ContainsKey returns false.

Part 3: We display the contents of the Dictionary we created and populated. We see that the strings from the List are the new keys.


Keys, Values. Often you may need to obtain a List of the keys in a Dictionary, which we see in this example. Also shown here is how to get a List of the values, although this requirement is much less common in my experience.

C# program that gets Keys and Values

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Popular example Dictionary. [1]
	Dictionary<string, int> birdDictionary = new Dictionary<string, int>();
	birdDictionary.Add("parakeet", 3);
	birdDictionary.Add("parrot", 5);
	birdDictionary.Add("finch", 7);
	birdDictionary.Add("lovebird", 9);

	// Get List of keys. [2]
	List<string> keyList = new List<string>(birdDictionary.Keys);
	// Display them.
	foreach (var value in keyList)
	{
	    Console.WriteLine(value);
	}

	// Get List of values. [3]
	List<int> valueList = new List<int>(birdDictionary.Values);
	// Display them.
	foreach (var value in valueList)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

parakeet
parrot
finch
lovebird

3
5
7
9

Part 1. Here we fill the Dictionary by calling the Add method with two arguments. This Dictionary instance happens to contain the names of pet birds. These are stored as string values.

Part 2. We use the List constructor on the Keys collection from the Dictionary. It accepts an IEnumerable collection with an element type of string. If your List has another value type, the element type will be different.

List Examples

Part 3: This part is the same as the previous part except it uses the List constructor with a parameter of the Values collection.


Summary. We looked at an easy way to convert a Dictionary into a List of KeyValuePair struct values. We further explored the interaction between the ToList method and the Dictionary type's implementation of IEnumerable.

Further: We saw a way you can put the elements in your List into a Dictionary, and ways you can put the elements of a Dictionary in a List.