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.

Download  Run Code

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.

Download  Run Code

 
Alternatively, you can convert each key-value pair into a string using the format specifier. For example,

Download  Run Code

That’s all about printing all key-value pairs in a dictionary in C#.