Introduction to Queues.
Queues are an interesting collection. Queues represent a first-in-first-out(FIFO) collection. Think of a queue like a line at a grocery store. Customers come to the check out and are processed in the order that they came in. If you needed to program that sort of situation you could use a queue.
Queues are used a lot in real life simulations. For example, you need to model how a bank processes customers to find out the best number of tellers to have at the windows at a given time. You would create a simulation that would process how many customers come into the bank, the average wait time of a custmoer. How many customers each teller processes.
You could also use a queue in a client-server application. As each request comes into the server it is put into a queue to be processed. The server would process the requests in the order that they came in.
This is how you would create a queue:
CODE
Queue<class> myQueue = new Queue<class>();
When you need to add an object to the queue you use the Enqueue method like this:
CODE
myQueue.Enqueue(object);
To get the first object in the queue you use the Dequeue method.
CODE
objectVariable = myQueue.Dequeue();
Sometimes you may want to see what the first object in the queue is without removing it from the queue. You would do this using the Peek method like this:
CODE
object = myQueue.Peek();
To determine how many objects are in a queue you would use the Count property like this:
CODE
intNumber = myQueue.Count;
If you need to empty the queue you would use the Clear method like this:
CODE
myQueue.Clear();
If you need to see the objects in your queue there two easy ways to do it. You can use a simple for loop or a foreach loop. This is how to do each one in turn:
CODE
for (int i = 0; i < myQueue.Count; i++)
{
Console.WriteLine(myQueue[i].ToString());
}
CODE
foreach (class o in myQueue)
{
Console.WriteLine(o.ToString());
}
This is a simple program that demonstrates the use of queues:
CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QueuesDemo
{
class Program
{
static void Main(string[] args)
{
Queue<string> myQueue = new Queue<string>();
myQueue.Enqueue("Bobby");
myQueue.Enqueue("Margaret");
myQueue.Enqueue("Timmy");
myQueue.Enqueue("Wendy");
myQueue.Enqueue("Linda");
WriteQueue(myQueue);
Console.ReadLine();
while (myQueue.Count > 0)
{
string name;
name = myQueue.Peek();
Console.WriteLine("Removing {0} form the queue\n\r", name);
myQueue.Dequeue();
WriteQueue(myQueue);
Console.ReadLine();
}
}
private static void WriteQueue(Queue<string> myQueue)
{
Console.WriteLine("This is the queue:");
if (myQueue.Count == 0)
Console.WriteLine("The queue is empty.");
foreach (string o in myQueue)
Console.WriteLine(o);
}
}
}