简体   繁体   中英

Removing the last item from a queue in C#

We have the Enqueue and Dequeue methods to work on a queue in C#. But is there a way we can remove the last item in the queue? Dequeue actually removes the item from the top.

The entire purpose of a Queue is to walk the collection from top to bottom. 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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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