Convert dictionary to List<KeyValuePair>

0 votes
asked Dec 29, 2010 by sean

I know that its possible to convert a List of KeyValuePair into a Dictionary, but is there a quick way (besides looping through manually) to perform the vice versa operation?

This would be the manual way,

foreach (KeyValuePair<double,double> p in dict)
{
    list.Add(new KeyValuePair<double,double>(p.Key,p.Value));
}

Not really that bad but I was just curious.

5 Answers

0 votes
answered Dec 29, 2010 by oded

Using linq:

myDict.ToList<KeyValuePair<double, double>>();

Dictionary elements are KeyValuePair items.

0 votes
answered Dec 29, 2010 by jason

To convert a Dictionary<TKey, TValue> to a List<KeyValuePair<TKey, TValue>> you can just say

var list = dictionary.ToList();

or the more verbose

var list = dictionary.ToList<KeyValuePair<TKey, TValue>>();

This is because Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>.

0 votes
answered Dec 29, 2010 by fejesjoco

Like Jason said. But if you don't really need a list, then you can just cast it to an ICollection<TKey, TValue> because it implements this interface, but some parts only explicitly. This method performs better because it don't copy the entire list, just reuses the same dictionary instance.

0 votes
answered Dec 1, 2014 by daniel-bogdan

For .NET 2.0:

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
List<KeyValuePair<TKey, TValue>> myList = new List<KeyValuePair<TKey, TValue>>(dictionary);
0 votes
answered Dec 7, 2015 by schwarrior

I've been trying enumerate an instance of Exception.Data which is an IDictionary. This is what finally worked:

    ICollection keys = idict.Keys;
    foreach(var key in keys)
    {
       var value = idict[key];
       Console.WriteLine("{0}: {1}", key, value);
    }
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...