Collections

Queues

A queue is a collection type that provides a first-in, first out API. The idea behind a queue, is that as you add items to the queue, you can remove them in the same order.

using System; using System.Collections.G...

Much like a list, a queue is backed by an array. Internally the queue manages the array and ensures that items are added at the end of it, and taken from the start of it. Here is a diagram to help make sense of this concept:

To declare a queue, you use the Queue<T> generic type, where T is your element type. So declare a queue of type string:

Queue<string> names = new Queue<string>();

The element type can be whatever type you want:

Queue<DateTime> calendar = new Queue<DateTime>();
Queue<int> sequence = new Queue<int>();

You can substitute var to allow the compiler to infer the type:

var names = new Queue<string>();

Adding items to the queue

The Queue<T> doesn't expose the usual Add or Remove methods like the other collection types. Instead the notion of

names.Enqueue("C3PO");

is expressed through the Enqueue method:

This will enqueue the new item at the end of the queue.

Removing items from the queue.

Much like the Enqueue method for adding items to the queue, the Queue<T> type provides an associated Dequeue method for removing those items. The items will be removed in the same order they are added.

string name = names.Dequeue();

If you call Dequeue and the queue is empty, then an InvalidOperationException will be thrown, so it's best to check the Count property to make sure items actually exist in the queue before calling Dequeue.

If you want to check the next item to come out of the queue without removing it, you can use the Peek method.

Looping through the queue

Like all other collections, you can use the for-each iterator to move through the queue, but as an alternative, you can use a combination of the while loop with a check against the Count property before you dequeue the next item:

while (names.Count > 0)
{
    string name = names.Dequeue();
    Console.WriteLine(name);    
}

 

Page 17 of 31