Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

C# Queues


  • Please log in to reply
No replies to this topic

#1 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 20 August 2011 - 08:33 AM

C# Queue

The Queue is a data structure that maintains First-In, First-Out order (FIFO). The idea is that items added to a queue are removed in the order they are added to the queue. Some uses of this structure are for scheduling and printing. For instance, documents are printed in order they are sent to the printer. The queue is also useful in implementation of many algorithms for other data structures such as the breadth-first search for graphs and some tree iteration algorithms.

Creating a Queue


The Queue class is located in the System.Collections.Generics namespace so make sure you using that namespace.

using System.Collections.Generics;

Example of a queue:

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

This queue is just for integers. Since the queue is a generic class you can use any data type you wish in the queue.

Adding Items to Front of Queue

This is as simple as calling the Enqueue method which adds an item to back of the queue.

Example:

q.Enqueue(3);

The queue now looks like this:

Queue1.jpg

Now one item is in the queue. If we want to add another one to the end of the queue we simply call Enqueue again.
q.Enqueue(5);

The queue now looks like this:

queue2.jpg

Removing Items From Queue

To remove an item from a queue we simply call the dequeue method. Like this:

 int front = q.Dequeue();
 Console.WriteLine(front);

The output is:

3


And the queue now looks like this:

queue3.jpg

Peek method

The peek method is used to look at the item in the front of the queue without removing it.

Example:

 Console.WriteLine(q.Peek());
 Console.WriteLine(q.Peek());

The output should be:

5
5


Emptying a Queue

We can clear the contents of a queue using the Clear() method. Example:

 q.Clear()

At this point, we can introduce the q.Count property to check if a queue is empty.

if (q.Count == 0)
{
     Console.WriteLine("q is empty.");
}
else
{
     Console.WriteLine("q is not empty.");
} 

As always post if you have any questions. :)
  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download