C#如何显示队列(Queue)中存储的所有客户元素?
问题原因
你当前使用的Peek()方法仅会返回队列的队首元素,不会遍历队列内的全部元素,因此只能打印出第一个入队的Jim,无法展示其他排队人员。
解决方案
推荐你使用以下两种不修改队列原有数据的方式输出全量排队人员:
- foreach 遍历输出
Queue 类实现了IEnumerable<T>接口,可以直接用foreach循环遍历所有元素,不会改变队列内的元素顺序和内容,把你原来输出姓名的代码替换为以下内容即可:
Console.WriteLine("The names of those in line at the bank are: "); foreach (var customer in customers) { Console.WriteLine(customer); }
- 用 string.Join 拼接后一次性输出
如果希望把所有姓名拼接为一行、用分隔符隔开展示,可以直接调用string.Join方法处理队列:
Console.WriteLine("The names of those in line at the bank are: " + string.Join("、", customers));
注意事项
如果你选择循环调用Dequeue()方法输出元素,会依次移除队首元素,执行完队列会被清空,如果你后续还要使用队列内的元素不建议采用该方案。
完整可运行示例代码
using System; using System.Collections.Generic; namespace QueueDemo { class Program { static void Main(string[] args) { Queue<string> customers = new Queue<string>(); customers.Enqueue("Jim"); customers.Enqueue("Bob"); customers.Enqueue("Susan"); customers.Enqueue("Liz"); customers.Enqueue("Mary"); Console.WriteLine("银行排队总人数为:"); Console.WriteLine(customers.Count); // 遍历输出所有排队人员 Console.WriteLine("排队人员姓名分别为:" + string.Join("、", customers)); customers.Enqueue("Andyn"); customers.Enqueue("Rhonda"); customers.Dequeue(); customers.Dequeue(); customers.Dequeue(); Console.WriteLine("当前剩余排队人数为:" + customers.Count); Console.WriteLine("当前排在第一位的人员为:" + customers.Peek()); Console.ReadKey(); } } }
内容的提问来源于stack exchange,提问作者user17019895
相关产品推荐
相关产品推荐

