C# – How to Print a Dictionary
This post shows you how to print a Dictionary
object in C#. We will need to do this when we want to print the data of the Dictionary object to View, or even print data to Output window of Visual Studio for debugging purposes, etc.
Let’s consider the below code.
Program.cs
using System;
using System.Collections.Generic;
namespace ByteNota
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> animalAges = new Dictionary<string, int>();
animalAges.Add("Lion", 35);
animalAges.Add("Elephant", 70);
animalAges.Add("Rabbit", 9);
animalAges.Add("Macaw", 50);
animalAges.Add("Fox", 14);
// print the dictionary to console
string output = "";
foreach (KeyValuePair<string, int> kvp in animalAges)
{
output += string.Format("Name = {0}, Age = {1}", kvp.Key, kvp.Value);
output += "\n";
}
Console.WriteLine(output);
}
}
}
In the above code, we define a sample animalAges
Dictionary object, iterate through the object and print the data out to Console window.
Output:
Name = Lion, Age = 35
Name = Elephant, Age = 70
Name = Rabbit, Age = 9
Name = Macaw, Age = 50
Name = Fox, Age = 14