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!
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:
When the documentation talks about calling GetEnumerator, it means on the IEnumerable that was returned by Reverse():
Of course, there’s rarely any need to get the enumerator like this, because
foreachwill do it for us under the covers:Or indeed, as in my first example, we can pass the reversed enumerable to a collection constructor such as
QueueorListand let it perform the iteration: