3

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!

5
  • 5
    Well sure, you can loop over them easily, printing each entry. What have you tried, and what happened? If you don't want to put the loop more than once, you can write a method to do that... Commented Nov 5, 2016 at 18:21
  • 1
    Why do you have a Java tag if this question is about C#? Commented Nov 5, 2016 at 18:23
  • Did you get it to work? Commented Nov 5, 2016 at 18:27
  • Possible duplicate of C# - Print dictionary Commented Nov 5, 2016 at 18:36
  • Yes, I got it to work. Thanks to all. Sorry about the java tag, was a mistake! Commented Nov 5, 2016 at 20:25

5 Answers 5

6

Try using the foreach:

foreach (var res in Employees) { Console.WriteLine("Employee with key {0}: ID = {1}, Name = {2}", res.Key, res.Value.Id, res.Value.Name); } 

or, simply using LINQ:

var output = String.Join(", ", Employees.Select(res => "Employee with key " + res.Key + ": ID = " + res.Value.Id + ", Name = " + res.Value.Name)); 
Sign up to request clarification or add additional context in comments.

Comments

4

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}"); } 

Comments

3

You can use the foreach loop to print all the value inside the Dictionary.

foreach(var employe in Employees) { Console.WriteLine(string.Format("Employee with key {0}: Id={1}, Name= {2}",employe.Key, employe.Value.Id, employe.Value.Name )); } 

Comments

1

You can define an IDictionary reference, and make it point to a Dictionary object

IDictionary<int, Employee> employees = new Dictionary<int,Employee>(); employees.Add(1, new Employee(1, "John")); //add the rest of the employees 

to loop through the dictionary, you can use

foreach(KeyValuePair<int, Employee> entry in employees) { Console.WriteLine("Employee with key "+entry.Key+": Id="+entry.Value.GetId()+", Name= "+entry.Value.GetName()); } 

This is similar to Java's HashMap<>.

Comments

1
var items = Employees.Select(kvp => string.Format("Employee with key {0} : Id={1}, Name={2}", kvp.Key, kvp.Value.Id, kvp.Value.Name); var text = string.Join(Environment.NewLine, items); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.