Creating Queues


Queues are dynamic lists in which the first item put into the collection is the first object extracted from it. Items from the queue can only be extracted in the order in which they were added.

To create a queue, add items to it, and remove items from it:

  1. Type System.Collections.Queue .

  2. Type the name of the queue variable that is to store the queue object, for example: msgs .

  3. Type = .

  4. Type new System.Collections.Queue() .

  5. Type a semicolon ; .

  6. Type msgs.Enqueue("Task1"); where "Task1" is the item to add to the queue.

  7. Type msgs.Dequeue(); to extract the first item in from the queue ( Figure 9.54 ).

    Figure 9.54 With queues you Enqueue and Dequeue. Enqueue puts elements at the bottom of the list, Dequeue removes the first element in the queue (first infirst out).
     void Task() {    System.Collections.Queue q1 = new    System.Collections.Queue();    q1.  Enqueue  ("Task1");    q1.  Enqueue  ("Task2");    q1.  Enqueue  ("Task3");    string s1 = (string)q1.  Dequeue  (); //Task1    string s2 = (string)q1.  Dequeue()  ; //Task2    string s3 = (string)q1.  Dequeue()  ; //Task3 } 

graphics/tick.gif Tip

  • You can also examine all of the items in the queue one by one, without removing them using the foreach notation ( Figure 9.55 ).

    Figure 9.55 foreach lets you navigate through the elements without removing them from the queue.
     void Task() {    System.Collections.Queue q1 = new    System.Collections.Queue();    q1.Enqueue("Task1");    q1.Enqueue("Task2");    q1.Enqueue("Task3");  foreach (string task in q1)   {   Response.Write(task + ",");   //Prints: Task1, Task2, Task3,   }  } 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net