Home
Map
Convert Dictionary to ListConvert Dictionary and List instances using ToList, Keys and Values.
C#
This page was last reviewed on Jun 14, 2021.
Convert Dictionary, List. In C# a Dictionary can be converted into a List. It is converted to a List of pairs—this requires the ToList extension method.
C# conversion info. 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.WriteLine
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); } } }
cat 1 dog 4 mouse 2 rabbit -1
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.
Detail This method avoids the chance of an exception being raised. If we access a key directly, we might get an exception.
Dictionary 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.
using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: create new List. List<string> list = new List<string>(); list.Add("Olympics"); list.Add("Nascar"); list.Add("Super Bowl"); list.Add("Wimbledon"); // Part 2: put List values into Dictionary. var exampleDictionary = new Dictionary<string, int>(); foreach (string value in list) { if (!exampleDictionary.ContainsKey(value)) { exampleDictionary.Add(value, 1); } } // Part 3: display Dictionary. foreach (var pair in exampleDictionary) { Console.WriteLine(pair); } } }
[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.
using System; using System.Collections.Generic; class Program { static void Main() { // Part 1: example Dictionary. Dictionary<string, int> birdDictionary = new Dictionary<string, int>(); birdDictionary.Add("parakeet", 3); birdDictionary.Add("parrot", 5); birdDictionary.Add("finch", 7); birdDictionary.Add("lovebird", 9); // Part 2: get List of keys. List<string> keyList = new List<string>(birdDictionary.Keys); // Display them. foreach (var value in keyList) { Console.WriteLine(value); } // Part 3: get List of values. List<int> valueList = new List<int>(birdDictionary.Values); // Display them. foreach (var value in valueList) { Console.WriteLine(value); } } }
parakeet parrot finch lovebird 3 5 7 9
Notes, ToList. The ToList extension method acts upon an IEnumerable generic collection. The Dictionary implements the IEnumerable interface with type parameter KeyValuePair.
Thus The Dictionary's implementation allows the ToList extension method to work here.
IEnumerable
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.
Detail It is faster to loop over and requires less memory due to its lack of an internal buckets structure.
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.
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 Jun 14, 2021 (edit).
Home
Changes
© 2007-2024 Sam Allen.