简体   繁体   English

从 C# 中的队列中删除最后一项

[英]Removing the last item from a queue in C#

We have the Enqueue and Dequeue methods to work on a queue in C#.我们有 Enqueue 和 Dequeue 方法来处理 C# 中的队列。 But is there a way we can remove the last item in the queue?但是有没有办法删除队列中的最后一项? Dequeue actually removes the item from the top. Dequeue 实际上是从顶部移除项目。

The entire purpose of a Queue is to walk the collection from top to bottom. Queue的全部目的是从上到下遍历集合。 If you want a collection type that allows removing from the back too (or any place in the collection), use another collection type, a List<T> for example.如果您想要一个也允许从后面删除(或集合中的任何位置)的集合类型,请使用另一种集合类型,例如List<T>

Maybe you should consider using a Stack instead of a Queue.也许您应该考虑使用堆栈而不是队列。

Stack works similar to a queue but instead of the first in first out behaviour a stack is used when you need a last in first out solution for your objects堆栈的工作原理类似队列但不是先入先出的行为,当你需要先掉最后为对象堆栈使用

//This is an expensive operation, so I only do this rarely. People here getting mad and not answering... all you do is just use a second Queue to move everything to:

// original queue must already be filled up
Queue<Waypoint> waypoints = new Queue<Waypoint>();
// fill it up...

Queue<Waypoint> temp = new Queue<Waypoint>();
while (waypoints.Count > 0) // stop one short of the end
{
    temp.Enqueue(waypoints.Dequeue());
}
Waypoint wp = waypoints.Dequeue();
// get the last one and do what you desire to it...
// I modified mine and then added it back, this is not needed
temp.Enqueue(new Waypoint(wp.pos, (p.vectorPath[0] - wp.pos).normalized));

// necessary: you have waypoints empty now so you have to  swap it for temp:
waypoints = temp;

Like Patrick stated the queue is meant to be first in first out.正如帕特里克所说,队列是先进先出的。 Think of it like a printer queue, the first page that goes to into the printer queue is the first to be printed out.把它想象成一个打印机队列,进入打印机队列的第一页是第一个被打印出来的。

Look into using a List instead of an Array, I found lists a bit easier to manipulate with a bunch of extended methods that arrays do not have.考虑使用列表而不是数组,我发现使用数组没有的一组扩展方法更容易操作列表。 http://www.dotnetperls.com/list http://www.dotnetperls.com/list

Here is a link to how to remove the last item in a list which has a few different ways of accomplishing it.这是如何删除列表中最后一项的链接,该列表有几种不同的完成方式。

How to remove the last element added into the List? 如何删除添加到列表中的最后一个元素?

hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM