Queue class

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
Exam Prep. Guides
Exam 70-536 Study Guide

1. Types and collections

2. Process, threading,…
3. Embedding features
4. Serialization, I/O
5. .NET Security
6. Interop., reflection,…
7. Global., drawing, text

edit

Contents

What Is the Queue Class?

The Queue class represents a way of managing elements in a collection using the First In First Out (FIFO) technique for adding and removing elements. FIFO simply means that whichever element was added to the collection first will automatically be the one removed first.

FIFO In the Queue Class

Elements are added to the end of the collection and removed from the beginning. In this way the element that was added first will be the one removed or retrieved first.

Members

This class has several methods and properties associated with it. Below is a non-exhaustive list of its most important methods and properties.

  • Count - Public property that gets the number of elements in the Queue
  • Clear() - Method that removes all objects from the Queue
  • Contains() - Method that determines if an element is in the Queue
  • CopyTo() - Method that copies the Queue elements to an existing one-dimensional array
  • Dequeue() - Method that removes and returns the object at the beginning of the Queue
  • Enqueue() - Method that adds an object to the end of the Queue
  • GetEnumerator() - Method that returns an enumerator for the Queue
  • Peek() - Method that returns the object at the beginning of the Queue without removing it
  • ToArray() - Method that copies the elements to a new array


Adding and Removing Elements

Add elements to a queue using the Enqueue() method. Remove elements from a queue by using the Dequeue() method.


Code Examples

Create and Populate a Queue

// Create a queue
Queue multiplesOfFive = new Queue();
 
// populate the array with the first 10 multiples of 5
for (int i = 0 ; i < 10 ; i++) {
  multiplesOfFive.Enqueue( i * 5 );
}

Remove Elements From the Queue

// Create the queue
Queue primes = new Queue();
 
primes.Enqueue( 2 );
primes.Enqueue( 3 );
primes.Enqueue( 5 );
primes.Enqueue( 7 );
 
// Dequeue will return the first item that was added and remove it
 
// firstPrime will be 2
int firstPrime = (int) primes.Dequeue();
 
// secondPrime will be 3
int secondPrime = (int) primes.Dequeue();

View First Element Without Removing It

// Create the queue
Queue messages = new Queue();
 
messages.Enqueue( "Joe:Hey Joe..." );
messages.Enqueue( "Bob:I'll see you tommorrow" );
messages.Enqueue( "Jane:Yesterday, I was gone..." );
messages.Enqueue( "Karen:How are you?" );
 
// Peek will allow a the first item to be read without removing it
string firstMessage = (string) messages.Peek();
 
if( firstMessage.StartsWith( "Bob" ) ){
   
  messages.Dequeue();
 
  // Display message
  // ...
}


MSDN References


Today's Deals: Electronics

Personal tools