Basic Collections - Queues
(Page 3 of 6 )
Queues
Lists are great when you need functionality similar to arrays. However, collections aren't just substitutes for simple arrays. Another collection is called a queue. As its name suggests, it's similar to a line of people. The first person to get in line is the first person to get out of line, the second person to get in line is the second to get out of line, and so on. A queue is a first-in-first-out (FIFO) collection. We can create a (generic) queue like this:
Queue<int> genericQueue1 = new Queue<int>();
Accessing the elements of a queue is unlike accessing the elements of an array or list. Instead of adding elements and accessing them with their zero-based indexes, we enqueue and dequeue them. Let's enqueue two integers with the Enqueue method:
genericQueue1.Enqueue(11);
genericQueue1.Enqueue(12);
The Enqueue method adds the given object to the end of the queue. So, above, 11 is first in line, and 12 is second in line. We can access the first element in line with the Dequeue method. It removes and returns the first element in line. Here, we remove the first element:
int someInteger = genericQueue1.Dequeue();
Note that attempting to dequeue an element from an empty queue will raise an exception.
As was mentioned, Dequeue removes the first element. Sometimes, it may be necessary to examine the first element without removing it from the queue. This is made possible by the Peek method, which returns the first element in the queue without removing it:
int anotherInteger = genericQueue1.Peek();
We can, however, loop through the contents of a Queue without disturbing them:
foreach (int element in genericQueue1)
{
Console.WriteLine(element);
}
If we need to remove all of the elements from a Stack, the Clear method can be called:
genericQueue1.Clear();
Like List, Queue features a Contains method, which determines if the Queue contains a given element. Here, we search genericQueue1 for the number twelve:
bool twelveFound = genericQueue1.Contains(12);
It's also possible to convert a Queue into an array, just as with List:
int[] arrayFromQueue = genericQueue1.ToArray();
Next: Stacks >>
More ASP.NET Articles
More By Peyton McCullough