FIFO collections with Queue of T in .NET C#
September 13, 2017 Leave a comment
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.
First some terminology:
- Putting an item in front of the queue is called Enqueue
- Removing an item from the front of the queue is called Dequeue
- Looking at the front element in the queue without removing it is called Peek
The 3 most important methods of Stack are consequently named Enqueue, Dequeue and Peek that do exactly as it says in the above list.
Consider the following Guest class:
public class Guest { public string Name { get; set; } public int Age { get; set; } }
The following code example demonstrates all 3 methods:
Queue<Guest> guests = new Queue<Guest>(); guests.Enqueue(new Guest() { Age = 25, Name = "John" }); guests.Enqueue(new Guest() { Age = 24, Name = "Barbara" }); guests.Enqueue(new Guest() { Age = 24, Name = "Phil" }); guests.Enqueue(new Guest() { Age = 23, Name = "Fred" }); guests.Enqueue(new Guest() { Age = 26, Name = "Hannah" }); guests.Enqueue(new Guest() { Age = 27, Name = "Cindy" }); Debug.WriteLine("Full guest list in the queue:"); foreach (Guest guest in guests) { Debug.WriteLine("{0}, {1}", guest.Name, guest.Age); } Debug.WriteLine(""); Guest firstToLeave = guests.Dequeue(); Debug.WriteLine(string.Format("First to leave: {0}", firstToLeave.Name)); Debug.WriteLine("Guest list after the first goodbye:"); foreach (Guest guest in guests) { Debug.WriteLine("{0}, {1}", guest.Name, guest.Age); } Guest soonToLeave = guests.Peek(); Debug.WriteLine(string.Format("Just checking who'll leave next: {0}", soonToLeave.Name));
This produces the following output:
Full guest list in the queue:
John, 25
Barbara, 24
Phil, 24
Fred, 23
Hannah, 26
Cindy, 27
First to leave: John
Guest list after the first goodbye:
Barbara, 24
Phil, 24
Fred, 23
Hannah, 26
Cindy, 27
Just checking who’ll leave next: Barbara
View all various C# language feature related posts here.