Is iterating over a Queue<T> guaranteed to be in queue order?

心不动则不痛 提交于 2019-12-05 21:59:01

Yes. It is. A queue is a first-in, first-out collection and will be enumerated in order.

Documentation Proof:

Yes it is, from the MSDN Documenation of GetEnumerator, emphisis mine

Initially, the enumerator is positioned before the first element in the collection. At this position, Current is undefined. Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current.

Current returns the same object until MoveNext is called. MoveNext sets Current to the next element.

However that does not address what the first element in the collection will be. To answer that we need to go to the description of Queue itself:

Represents a first-in, first-out collection of objects.

Combining the two above statements we have the official code contract that the first object returned from the Enumerator will be the first element in the collection and the fact that the first element in the collection will be the first-in object added to the collection giving us our final output that iterating over a Queue<T> will always be in order.


As an aside, compare that to a Dictionary, the definition for GetEnumerator() states the same line about retrieving the first element first. However Dictionary's description does include the explicit ordering of objects in the collection:

Represents a collection of keys and values.

And that is why it is "legal" for a Dictionary not to return in insertion order.

Here is the MSDN page which describes GetEnumerator for Queue. In summary (as other's have said) you're good to go. http://msdn.microsoft.com/en-us/library/4a9449ty.aspx

Note that enumerating the queue this way does not change it's contents the way that looping over it calling Dequeue() would

Yes, iterating over a Queue<T> is guaranteed to be in the order items were added to it. This is the definition of a FIFO queue. From the MSDN docs:

Queues are useful for storing messages in the order they were received for sequential processing. Objects stored in a Queue are inserted at one end and removed from the other.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!