Everything You Need to Know About the .NET Queue Collection Type

The Queue collection type is a bit of a black sheep in the many different collection types. In some ways, it works exactly like you would expect any other .NET collection to work. However, in other ways, it seems to be very odd in its behavior. It will help if you remember that this is a Queue, not some ordinary collection.

What is a Queue?

A Queue is, in several ways, singular in its behavior. Yes, a Queue is a collection container. It can handle generics. What makes it different, though, is that once you put an object into a Queue, you have to be deliberate in how you remove it. The Queue collection type doesn’t have the usual Remove or RemoveAt extension methods. It doesn’t support indexers so queueItems[1] doesn’t work. It does support other extension methods such as Single and First.

Manipulating Queues

Queues support First-In-First-Out (FIFO) processing. You can only get items into the queue in one way: the Enqueue method. You can only remove items from the queue in one way: the Dequeue method.

Listing 1.1 – Adding Items to a Queue Using Enqueue

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

q.Enqueue("test-1");
q.Enqueue("test-2");
q.Enqueue("test-3");

This will add three items to the collection.

Listing 1.2 – Removing Items from a Queue Using Dequeue

while (q.Count() > 0)
{
    Console.WriteLine(q.Dequeue());
}

This will simply keep calling the Dequeue method until there isn’t anything left in the Queue. However, remember the FIFO principle. The first item in is the first item out. See the output below.

Listing 1.3 – Output from Listing 1.2

test-1
test-2
test-3

As I already mentioned, you can get to the objects in the Queue easily enough. If you have objects instead of simple strings as I have in this example, you can write LINQ queries to get objects such as below.

Listing 1.4 – Getting Objects In A Queue

var selectedItem = q.First(i => i == "test-2");

Console.WriteLine("Selected Item: " + selectedItem);

This, of course, will just print out test-2 to the console.

Conclusion

Again, the Queue collection container is a bit odd but it definitely has valid use cases, mainly when the FIFO manner of objects needs to be preserved.

Leave a Reply

Your email address will not be published.