Dictionary to string C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Program { static void Main(string[] args) { //initialize a dictionary with keys and values. Dictionary<int, string> birds = new Dictionary<int, string>() { {1,"White Stork"}, {2,"Jabiru"}, {3,"Marabou Stork"}, {4,"Scarlet Ibis"} }; Console.WriteLine("dictionary elements.........."); foreach (KeyValuePair<int, string> pair in birds) { Console.WriteLine(pair.Key + " ........ " + pair.Value); } //create a stringbuilder. StringBuilder sb = new StringBuilder(); //append dictionary key value to stringbuilder. foreach (KeyValuePair<int, string> pair in birds) { sb.Append(pair.Key); sb.Append("["); sb.Append(pair.Value); sb.Append("]"); sb.Append(","); } Console.WriteLine("dictionary elements to string....."); Console.WriteLine(sb.ToString().TrimEnd(',')); Console.ReadLine(); } } |
Output:

How to convert a Dictionary to a string in C#