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.
Finally:We print all the Key and Value properties with the Console.WriteLine method.
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