Is this guaranteed to always print 123
?
Queue<string> theQueue = new Queue<string>();
theQueue.Enqueue("1");
theQueue.Enqueue("2");
theQueue.Enqueue("3");
foreach(var str in theQueue)
{
Console.Write(str);
}
Console.WriteLine();
Edit:
I totally agree that a queue that enumerated in any other order would be obviously incorrect. That's why I asked the question. However, the abstract data type queue
only makes guarantees about its enqueue
and dequeue
operations.
I'm looking for an answer that references documentation that guarantees this ordering in the .NET BCL.
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.
来源:https://stackoverflow.com/questions/18451710/is-iterating-over-a-queuet-guaranteed-to-be-in-queue-order