打印字典值的简便方法?

时间:2016-11-05 18:18:46

标签: c# dictionary

我有以下代码:

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

有一种简单的方法可以像Java一样轻松地打印字典的值吗?例如,我希望能够打印如下内容:

  

拥有密钥1的员工:Id = 1,Name = John

     

拥有密钥2的员工:Id = 2,Name = Henry

..等..

谢谢。

抱歉,我习惯了Java!

5 个答案:

答案 0 :(得分:3)

您可以使用foreach语句:

foreach(var pair in Employees)
{
    Console.WriteLine($"Employee with key {pair.Key}: Id={pair.Value.Id} Name={pair.Value.Name}");
}

答案 1 :(得分:2)

您可以使用foreach循环打印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 ));
} 

答案 2 :(得分:2)

尝试使用foreach

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

或者,简单地使用LINQ:

var output = Employees.Select(res => "Employee with key " + res.Key + ": ID = " + res.Value.Id + ", Name = " + res.Value.Name);

答案 3 :(得分: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);

答案 4 :(得分:0)

您可以定义IDictionary引用,并将其指向Dictionary对象

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

循环遍历字典,可以使用

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

这类似于Java的HashMap<>