Search code examples
c#.netqueuereverseenumerator

Reverse a Queue


I'm using the extension menthod Reverse(), but it does not seem to be doing anything. The MSDN states it is implemented as a deferred execution, however I can't seem to get this to work.

Here is how I call it.

        Queue<T> currentPath = new Queue<T>();
        currentPath.Enqueue(someValue);
        currentPath.Enqueue(someValue2);

        currentPath.Reverse();

This is what the MSDN says:

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

I'm not sure what it means by calling GetEnumerator. I've tried that by simply doing the following with no avail:

currentPath.Reverse();
currentPath.GetEnumerator();

I've a feeling I'm doing something quite silly here, any help would be appreciated!


Solution

  • Reverse returns the reversed sequence. It doesn't modify the original. Try something like this, to construct a new Queue out of the reversed items:

    currentPath = new Queue<T>(currentPath.Reverse());
    

    When the documentation talks about calling GetEnumerator, it means on the IEnumerable that was returned by Reverse():

    IEnumerable reversed = currentPath.Reverse();
    IEnumerator reversedEnumerator = reversed.GetEnumerator();
    // Now reversedEnumerator has assembled the reversed sequence,
    // we could change the contents of currentPath and it wouldn't
    // affect the order of items in reversedEnumerator.
    

    Of course, there's rarely any need to get the enumerator like this, because foreach will do it for us under the covers:

    IEnumerable reversed = currentPath.Reverse();
    foreach (var item in reversed)
    {
        // ...
    }
    

    Or indeed, as in my first example, we can pass the reversed enumerable to a collection constructor such as Queue or List and let it perform the iteration:

    currentPath = new Queue<T>(currentPath.Reverse());