HomeSearch

C# Convert Dictionary to List

Convert Dictionary and List instances using ToList, Keys and Values.
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.
Notes, conversions. The ToList method is part of the System.Linq extensions to the C# language. It can be used for many requirements, and helps with conversions.
To start, we include the System.Collections.Generic and System.Linq namespaces. We create a Dictionary. Next we call ToList() on that Dictionary, yielding a List of KeyValuePair instances.ToList

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
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
Notes, ToList. 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.

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

ContainsKey: This method avoids the chance of an exception being raised. If we access a key directly, we might get an exception.

ContainsKey

Part 1: We add 4 string values. The List then has 4 elements. We need to add these 4 elements to the Dictionary next.

Part 2: We create a Dictionary with string keys. We loop through the List, calling 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.

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]
Keys, Values. Often we may need to obtain a List of the keys in a Dictionary. We can also get a List of the values. We must access the Keys, and Values, properties.

Part 1: Here we fill the Dictionary by calling the Add method with 2 arguments. We add the names of pet birds.

Part 2: We use the List constructor on the Keys from the Dictionary. It accepts an IEnumerable collection with an element type of string.

List

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

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
Notes, collections. There may be other methods in your program that require a List not a Dictionary. And 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 vs. List
A summary. We converted a Dictionary into a List of KeyValuePair struct values. We explored the interaction between ToList() and the Dictionary type's implementation of IEnumerable.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls