user127815 user127815 - 1 year ago 72
C# Question

Easy way to Print Values of a dictionary?

I have the below code:

static void Main(string[] args)
// Add 5 Employees to a Dictionary.
var Employees = new Dictionary<int, Employee>();
Employees.Add(1, new Employee(1, "John"));
Employees.Add(2, new Employee(2, "Henry"));
Employees.Add(3, new Employee(3, "Jason"));
Employees.Add(4, new Employee(4, "Ron"));
Employees.Add(5, new Employee(5, "Yan"));

Is there an easy way to print the values of the dictionaries in an easy way like in Java? For example, I want to be able to print something like:

Employee with key 1: Id=1, Name= John

Employee with key 2: Id=2, Name= Henry

.. etc..

Thank you.

Sorry, am used to Java!

Answer Source

You can use foreach statement:

foreach(var pair in Employees)
    Console.WriteLine($"Employee with key {pair.Key}: Id={pair.Value.Id} Name={pair.Value.Name}");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download