Easy way to Print Values of a dictionary?
10,139
Solution 1
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}");
}
Solution 2
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 ));
}
Solution 3
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));
Solution 4
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);
Author by
user127815
Updated on June 28, 2022Comments
-
user127815 almost 2 years
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!