Can anyone help me understand why the output of the two for loops below produce different outputs?
They to my eye are the same, however the original Dictionary object’s for loop outputs all 9 of its members, but the Queue objects for loop outputs just the first 5.
void test()
{
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(0, "http://example.com/1.html");
d.Add(1, "http://example.com/2.html");
d.Add(2, "http://example.com/3.html");
d.Add(3, "http://example.com/4.html");
d.Add(4, "http://example.com/5.html");
d.Add(5, "http://example.com/6.html");
d.Add(6, "http://example.com/7.html");
d.Add(7, "http://example.com/8.html");
d.Add(8, "http://example.com/9.html");
Queue<KeyValuePair<int, string>> requestQueue = new Queue<KeyValuePair<int, string>>();
// build queue
foreach (KeyValuePair<int, string> dictionaryListItem in d)
{
requestQueue.Enqueue(dictionaryListItem);
Console.WriteLine(dictionaryListItem.Value);
}
Console.WriteLine(" ");
for (int i = 0; i < requestQueue.Count; i++)
{
Console.WriteLine(requestQueue.Peek().Value);
requestQueue.Dequeue();
}
}
You need to save count before the loop:
The reason is that it is evaluated at each iteration of the for loop:
At the start of the first iteration,
requestQueue.Countis 9,iis0.2nd iteration:
requestQueue.Countis 8,iis1.3rd iteration:
requestQueue.Countis 7,iis2.4th iteration:
requestQueue.Countis 6,iis3.5th iteration:
requestQueue.Countis 5,iis4.6th iteration:
requestQueue.Countis 4,iis5. –> Exit loop.Note: The
Countof the queue is reduced with each iteration becauseQueue.Dequeueremoves the first item in the queue and returns it to the caller.