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.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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: