Using C# and VisualStudio. I'm trying to intrude everything in one function.
3 Answers
Check the Queue<T>.TryPeek(T)
Method

- 738
- 7
- 26
-
Wrong, you are thinking of a stack – TheGeneral Dec 01 '20 at 04:16
To get the last element you added to a Queue
, which means the last element that will be dequeued, you can just use Last
:
var queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
Console.WriteLine(queue.Last());
Output
3
Note : Peeking will not help, peeking a queue shows you the next dequable item
The long story is, a queue supports IEnumerbale<T>
public class Queue<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
Internally, it stores a queue as an array with a capacity and modulates around the array to get the next item so it doesn't need to copy all the time.
IEnumerable.Last
will iterate from head to tail using something similar to the following, until it reaches the last item. Which makes it safe to call.
internal T GetElement(int i)
{
return _array[(_head + i) % _array.Length];
}
Basically it's an O(n) operation. So, I've you have large queues take into consideration this is not all that efficient. Maybe you want a Stack Instead, or to keep the last item added in memory.
It is just a fancy array.

- 19,824
- 17
- 99
- 186

- 79,002
- 9
- 103
- 141
Try .Top(). Top() method shows the next element that will be popped in the queue.
Regards,

- 9
- 2