Convert a Dictionary to a List of KeyValuePair in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("White", "#FFFFFF"); dict.Add("Grey", "#808080"); dict.Add("Silver", "#C0C0C0"); dict.Add("Black", "#000000"); List<KeyValuePair<string, string>> mappings = dict.ToList(); Console.WriteLine(String.Join(", ", mappings)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("White", "#FFFFFF"); dict.Add("Grey", "#808080"); dict.Add("Silver", "#C0C0C0"); dict.Add("Black", "#000000"); List<KeyValuePair<string, string>> mappings = new List<KeyValuePair<string, string>>(); foreach (var mapping in dict) { mappings.Add(mapping); } Console.WriteLine(String.Join(", ", mappings)); } } |
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#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)