【问题标题】:How to display all customers in a queue in c#?如何在 C# 中显示队列中的所有客户?
【发布时间】:2021-10-02 22:20:14
【问题描述】:

所以我正在编写一个 c# 控制台,它使用队列来显示一行人。代码如下:

 customers.Enqueue("Jim");
                    customers.Enqueue("Bob");
                    customers.Enqueue("Susan");
                    customers.Enqueue("Liz");
                    customers.Enqueue("Mary");

                    Console.WriteLine("The number of the people in line at the bank is: ");
                 
                    Console.WriteLine(customers.Count);
                    Console.WriteLine("The names of those in line at the bank are: " + customers.Peek());

                    customers.Enqueue("Andyn");
                    customers.Enqueue("Rhonda");


                    customers.Dequeue();
                    customers.Dequeue();
                    customers.Dequeue();
                    Console.WriteLine("The number of shoppers now in line is:  " + customers.Count);
                    Console.WriteLine("The shopper currently first in line is: " + customers.Peek());

                    Console.ReadKey();

它运作良好,唯一的问题是当试图显示排队的人的名字时,它只显示吉姆。我想知道如何在行中显示其他人?谢谢。

【问题讨论】:

    标签: c# visual-studio console


    【解决方案1】:

    你可以使用 foreach 循环

    foreach (var customer in customers)
        {
            Console.WriteLine(customer);
        }
    

    结果

    Liz
    Mary
    Andyn
    Rhonda
    

    【讨论】:

    • 成功了,谢谢。
    • @user17019895 如果有用,请不要忘记接受答案。您可以通过单击答案一侧的复选标记来完成。
    • 从技术上讲,如果答案有用,则应单击向上箭头,如果答案是您使用的答案,则应单击复选标记。多个答案可能有用(并且应该被赞成),但您只能将一个标记为您使用的那个
    【解决方案2】:

    Queue 实现了 IEnumerable,这意味着您可以将其传递给 string.Join 以创建由公共分隔符连接的所有元素的单个字符串:

    var q = string.Join(",", customers);
    

    然后你可以打印出来

    【讨论】:

      猜你喜欢
      • 2015-01-03
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多