FIFO data structure in .NET: Queue of T
October 3, 2013 Leave a comment
If you need a generic collection where you are forced to handle the elements on a first come first served basis then Queue will be your friend. There’s no Insert, Add or Delete method and you cannot access just any particular element by some index, like [2]. This data structure is most applicable in First-in-first-out – FIFO – scenarios.
To initialise:
Queue<Client> clientsQueueingInShop = new Queue<Client>();
To add objects:
clientsQueueingInShop.Enqueue(new Client {Name = "Nice person"}); clientsQueueingInShop.Enqueue(new Client {Name = "My friend"}); clientsQueueingInShop.Enqueue(new Client {Name = "My neighbour"});
To retrieve the first object in the queue:
Client nextUp = clientsQueueingInShop.Dequeue();
This will not only get the first client – “Nice person” – in the queue but also remove it from the collection. So that the next time you call Dequeue() it will return “My friend”.
You can look at the next item in the queue by calling the Peek() method. It doesn’t remove the object from the collection, in other words it will return the same object on subsequent calls:
Client nextUp = clientsQueueingInShop.Peek();
You can query the queue to see if it contains a particular element:
bool contains = clientsQueueingInShop.Contains(myFavouriteClient);
You will need to make sure of course that the objects are comparable in the queue.
In case you absolutely must access an object in the queue by some index one option is to convert the queue to an array:
Client[] clientArrays = clientsQueueingInShop.ToArray();
This will create a copy of the queue as an array, the original queue remains intact.