Книга: C# 2008 Programmer

Queues

Queues

The queue is a first in, first out (FIFO) data structure. Unlike the stack, items are removed based on the sequence that they are added.

In .NET, you can use the Queue class (or the generic equivalent of Queue<T>) to represent a queue collection. The following statement creates an instance of the Queue class of type string:

Queue<string> tasks = new Queue<string>();

To add items into the queue, use the Enqueue() method. The following statement inserts four strings into the tasks queue:

tasks.Enqueue("Do homework");
tasks.Enqueue("Phone rings");
tasks.Enqueue("Get changed");
tasks.Enqueue("Go for movies");

To retrieve the elements from a queue, you can use either the Peek() method or the Dequeued method. Peek() returns the object at the beginning of the queue without removing it. Dequeue() removes and returns the object at the beginning of the queue:

Console.WriteLine(tasks.Peek()); //---Do homework---
Console.WriteLine(tasks.Dequeue());-- //---Do homework---
Console.WriteLine(tasks.Dequeue());-- //---Phone rings---
Console.WriteLine(tasks.Dequeue());-- //---Get changed---
Console.WriteLine(tasks.Dequeue());-- //---Go for movies---

If a queue is empty and you try to call the Dequeue() method, an InvalidOperationException error occurs, so it is useful to check the size of the queue using the Count property before you perform a dequeue operation:

if (tasks.Count < 0)
 Console.WriteLine(tasks.Dequeue());
else
 Console.WriteLine("Tasks is empty");

To extract all the objects within a Queue object without removing the elements, use the foreach statement, like this:

foreach (string t in tasks) Console.WriteLine(t);

Here's what prints out:

Do homework
Phone rings
Get changed
Go for movies

Оглавление книги


Генерация: 6.467. Запросов К БД/Cache: 2 / 0
поделиться
Вверх Вниз