Working with System.Collections.Queue in C#

In the last post, Working with System.Collections.SortedList, we have seen how to work with SortedList using C#. In this article I will explore Queue class and the methods provided.

Queue, is a simple class which represents first-in, first-out collection of objects and behaves exactly like, any queue in normal life should behave.

Here is class signature as at MSDN.

public class Queue : ICollection, IEnumerable, 

Here is how we can declare and initialize a Queue object

            // declare Queue
            Queue queue;

            // initiatlize with initial capacity 
            queue = new Queue(10);

            // initiatlize with initial capacity 
            // and grow factor
            queue = new Queue(10, 5);

            // initiatlize with a collection
            queue = new Queue(new String[5]);

            // default initialization
            queue = new Queue();

This is how to add am object to a Queue. An object could be added to the end only

 // Add an object to the tail

This is how to remove an object from a Queue. An object could be removed from front only

 // remove an object from front

Here are remaining methods provided with a bit of details for what they can do for us

            // Return an Object at the front, // without removing
            object value = queue.Peek();

            // filter and get item as per type from Queue
            IEnumerable queueEnummerable = queue.OfType<string>();

            // compare with another object
            bool IsEqualTo = queue.Equals(queue);

            // get an instance of type IQquerable
            IQueryable querable = queue.AsQueryable();

            // use Cast<T> to convert to another Collection
            List<string> list = queue.Cast<string>().ToList();

            // clear an Queue

            // Check if Queue contains an object

            // copy the contents into an Array
            string[] tempArray = new string[3];
            queue.CopyTo(tempArray, 0);

            // get total number of items in Queue
            int numberOfItems = queue.Count;

            // Get and use IEnumerator from Queue
            IEnumerator e = queue.GetEnumerator();
            while (e.MoveNext())
                Object obj = e.Current;

            // get type

            // convert to an Array of Type T

            // get a string representation

One thought on “Working with System.Collections.Queue in C#

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s