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

1. Using String.Join() method

The String.Join() method from the System.Linq namespace is commonly used to concatenate elements of the specified sequence using the specified separator. You can use the Select() method as a helper while joining each key-value pair in a dictionary with a delimiter.

Download  Run Code

 
Instead of calling the ToString() method, you can format the key-value pair as desired. The following solution demonstrates this by using the LINQ Query syntax to project over the dictionary mappings.

Download  Run Code

2. Using Enumerable.Aggregate() method

Alternatively, you can use the LINQ’s Aggregate() method, which applies an accumulator function on each element of a sequence. It can be used as follows to stringify a dictionary.

Download  Run Code

3. Using StringBuilder.Append() method

Finally, you can write your custom logic to stringify a dictionary. The idea is to iterate over the dictionary using a foreach loop and append all the dictionary entries to a StringBuilder using its Append() method. Then, invoke the ToString() method to get the string representation.

Download  Run Code

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