Print all key-value pairs in a Dictionary in C#
This post will discuss how to print all key-value pairs in a dictionary in C#.
1. Using foreach loop
The idea is to iterate over the dictionary using a regular foreach loop and print all key-value pairs, as the following example illustrates.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4} }; foreach (var kvp in dict) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } } } |
Output:
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
2. Using Enumerable.Select() Method
If you need to just display key-value pairs present in the dictionary, you can get the string representation of the dictionary containing all key-value pairs. This transformation can be easily done using the LINQ’s Select() method. Note that you need to include System.Linq namespace.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4} }; var str = String.Join(", ", dict.Select(kvp => "{" + kvp.Key + "=" + kvp.Value.ToString() + "}")); Console.WriteLine(str); // {A=1}, {B=2}, {C=3}, {D=4} } } |
Alternatively, you can convert each key-value pair into a string using the format specifier. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { Dictionary<string, int> dict = new Dictionary<string, int>() { {"A", 1}, {"B", 2}, {"C", 3}, {"D", 4}, {"E", 5} }; var str = String.Join(", ", dict.Select(kvp => string.Format("[{0}, {1}]", kvp.Key, kvp.Value))); Console.WriteLine(str); // [A, 1], [B, 2], [C, 3], [D, 4], [E, 5] } } |
That’s all about printing all key-value pairs in a dictionary 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 :)