C# queue
A queue represents a collection of first-in, first-out objects. Queues are used when you need first-in, first-out access to items. When you add an item to the list, it is called queuing, and when you remove an item from the list, it is called queuing.
Methods and properties of the Queue class
The following table lists some common properties of Queue
class:
Attribute |
Description |
---|---|
Count |
Gets the number of elements contained in the Queue. |
The following table lists some common methods of Queue
:
Serial number |
Method name & description |
---|---|
1 |
Public virtual void Clear (); removes all elements from the Queue. |
2 |
Public virtual bool Contains (object obj); determines whether an element is in Queue. |
3 |
Public virtual object Dequeue (); removes and returns the object at the beginning of Queue. |
4 |
Public virtual void Enqueue (object obj); add an object to the end of the Queue. |
5 |
Public virtual object [] ToArray (); copy Queue into a new array. |
6 |
Public virtual void TrimToSize (); sets the capacity to the actual number ofelements in the Queue. |
Example
The following example demonstrates the use of Queue:
Example
using System;
using System.Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
q.Enqueue('A');
q.Enqueue('M');
q.Enqueue('G');
q.Enqueue('W');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
q.Enqueue('V');
q.Enqueue('H');
Console.WriteLine("Current queue: ");
foreach (char c in q)
Console.Write(c + " ");
Console.WriteLine();
Console.WriteLine("Removing some values ");
char ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
ch = (char)q.Dequeue();
Console.WriteLine("The removed value: {0}", ch);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
Current queue:
A M G W
Current queue:
A M G W V H
Removing values
The removed value: A
The removed value: M