Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reverse iterate over Queue?

Tags:

c#

foreach loop iterates over Queue starting from the oldest item and ending with newest. What if I need to start with newest and end with oldest (probably interrupting at some point as in most cases I just need to iterate over several newest items)?

i'm looking for straighforward and efficient solution. without recreating new objects.

like image 831
Oleg Vazhnev Avatar asked Jun 13 '26 06:06

Oleg Vazhnev


2 Answers

You could use Linq's Reverse() function:

Queue myQueue;

foreach (var item in myQueue.Reverse())
{
    // do things
}
like image 137
Fabian Tamp Avatar answered Jun 14 '26 19:06

Fabian Tamp


Both Reverse() and ToArray() have bad performance. If possible, change Queue<T> to LinkedList<T>.

LinkedList works like a deque (https://en.wikipedia.org/wiki/Double-ended_queue).

More details: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1

like image 36
Robin Qiu Avatar answered Jun 14 '26 18:06

Robin Qiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!