FIFO collections with Queue of T in .NET C#

FIFO, that is first-in-first-out, collections are represented by the generic Queue of T class in .NET. Queues are collections where a new element is placed on top of the collection and is removed last when the items are retrieved.

Let’s say that you’re throwing a party where you follow a Queue policy as far as guests are concerned. As time goes by you’d like all of them to leave eventually and the first one to go will be the first person who has arrived. This is probably a fairer policy than what we saw in the post on stack collections.

Read more of this post

Advertisements

FIFO data structure in .NET: Queue of T

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.

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: