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.
You could use Linq's Reverse() function:
Queue myQueue;
foreach (var item in myQueue.Reverse())
{
// do things
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With