Convert dictionary to List<KeyValuePair>

C#GenericsCollections

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Using linq:

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

Dictionary elements are KeyValuePair items.

Solution 3 - C#

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.

Solution 4 - C#

For .NET 2.0:

Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();
List<KeyValuePair<TKey, TValue>> myList = new List<KeyValuePair<TKey, TValue>>(dictionary);

Solution 5 - C#

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);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSeanView Question on Stackoverflow
Solution 1 - C#jasonView Answer on Stackoverflow
Solution 2 - C#OdedView Answer on Stackoverflow
Solution 3 - C#fejesjocoView Answer on Stackoverflow
Solution 4 - C#Daniel BogdanView Answer on Stackoverflow
Solution 5 - C#SchwarriorView Answer on Stackoverflow