This post will discuss how to convert a Dictionary<TKey,TValue> to a List<KeyValuePair> in C#.

1. Using Dictionary<TKey,TValue>.ToList() Method

A simple solution is to use ToList() method to create a List<KeyValuePair> from a Dictionary<TKey,TValue>. It is available in LINQ and you need to add System.Linq namespace.

Download  Run Code

Output:

[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]

2. Using foreach loop

Another option is to create a new list of KeyValuePair, iterate over the Dictionary<TKey,TValue>, and manually add each KeyValuePair to the new dictionary. This can be easily done using the foreach loop, as demonstrated below. Note that this doesn’t uses LINQ.

Download  Run Code

Output:

[White, #FFFFFF], [Grey, #808080], [Silver, #C0C0C0], [Black, #000000]

That’s all about converting a Dictionary<TKey,TValue> to a List of KeyValuePair in C#.