【问题标题】:Easy way to Print Values of a dictionary?打印字典值的简单方法?
【发布时间】:2016-11-05 18:18:45
【问题描述】:

我有以下代码:

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!

【问题讨论】:

  • 当然,您可以轻松地遍历它们,打印每个条目。你试过什么,发生了什么?如果您不想多次放置循环,则可以编写一个方法来执行此操作...
  • 如果这个问题是关于 C# 的,为什么还要有 Java 标签?
  • 你让它工作了吗?
  • C# - Print dictionary的可能重复
  • 是的,我让它工作了。谢谢大家。抱歉,java 标签是一个错误!

标签: c# dictionary


【解决方案1】:

尝试使用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 = String.Join(", ", Employees.Select(res => "Employee with key " + res.Key + ": ID = " + res.Value.Id + ", Name = " + res.Value.Name));

【讨论】:

    【解决方案2】:

    你可以使用foreach语句:

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

    【讨论】:

      【解决方案3】:

      您可以使用 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 ));
      } 
      

      【讨论】:

        【解决方案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);
        

        【讨论】:

          【解决方案5】:

          您可以定义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&lt;&gt;

          【讨论】:

            猜你喜欢
            • 2021-12-19
            • 2018-08-29
            • 1970-01-01
            • 2015-12-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-10-03
            • 1970-01-01
            相关资源
            最近更新 更多