Tuesday, September 21, 2010

Working with Queue:


Working with Queue:

Queue class which is available in System.Collections namespace, represents First – in – First Out(FIFO) Collections of objects. Queue size increases dynamically as we add elements to it. Queue has two general methods Enqueue and Dequeue by using which we can maintain the elements in the collection.
Common Methods used in Queue
Push():
Is used to add elements to the Queue.
Insert elements into Queue:
 Queue Products = new Queue();
 Products.Enqueue("FM Transmitter");
 Products.Enqueue("DJ Cable");
 Products.Enqueue("Power Adapter");
Add an array to Queue:
string [ ]products = new string[3]{ "Transmitter", "DJ Cable ", "Power Adapter " };
Queue Products = new Queue();
Products.Enqueue(products);

Pop():
Removes and returns the element at the top of the Queue. The following code shows the functionality of pop().
Queue Products = new Queue();
Products.Enqueue("FM Transmitter");
Products.Enqueue("DJ Cable");
Products.Enqueue("Power Adapter");
Console.WriteLine("{0}", Products.Contains("DJ Cable"));
Console.WriteLine("Before Dequeue()");
foreach (string s in Products)
   {
    Console.WriteLine(s)      
   }
Console.WriteLine("===============");          
Console.WriteLine("Pop out element:{0}", Products.Dequeue());
Console.WriteLine("=================\n After Dequeue()");
foreach (string s in Products)
    {
         Console.WriteLine(s);
    }

Peek:
Is used to return the top element from the Queue without removing it.
Queue Products = new Queue();
Products.Enqueue("FM Transmitter");
Products.Enqueue("DJ Cable");
Products.Enqueue("Power Adapter");
Console.WriteLine("{0}", Products.Peek()); 

Contains():
Returns a boolean value which is used to determine whether an element is in the list.
Queue Products = new Queue();
Products.Enqueue("FM Transmitter");
Products.Enqueue("DJ Cable");
Products.Enqueue("Power Adapter");
Console.WriteLine("{0}",Products.Contains("DJ Cable"));

CopyTo():
Is used to copies entire elements in the Queue to an existing one dimensional array.
string[ ] products = new string[ 3 ];
Queue Products = new Queue();
Products.Enqueue("FM Transmitter");
Products.Enqueue("DJ Cable");
Products.Enqueue("Power Adapter");
Products.CopyTo(products, 0);
foreach (string s in products)
    {
       Console.WriteLine("{0}", s);
    }

Next:
Working with HashTable.

Furhter Reading:

No comments:

Post a Comment