Queue is a type of collection in which the item stored first is retrieved first. This behaviour is also called as FIFO i.e. First In First Out.
Inserting an item into a Queue is called as Enqueuing and removing an item is called as Dequeuing.
Important features of C# Queue class
Below are some of the important features of a Queue class.
- Null values can be stored in Queue.
- Duplicate values can be stored in Queue.
- It has both generic and non-generic versions.
Create a Queue in C#
A Queue can be created by using the below code.
Queue serviceStation = new Queue();
Add items to a C# Queue
To add items to a Queue the Enqueue method is used.
serviceStation.Enqueue("A");
Remove items from a C# Queue
To remove items from a Queue the Dequeue method is used.
Since it follows the FIFO pattern so the items added first to the queue will be removed first.
serviceStation.Dequeue();
Foreach loop to access items in a C# Queue
To access all the items stored in a Queue a foreach loop can be used.
Queue serviceStation = new Queue();
serviceStation.Enqueue("A");
serviceStation.Enqueue("B");
serviceStation.Enqueue("C");
foreach (object obj in serviceStation)
{
Console.WriteLine("Item: " + obj);
}
Output:
Item: A
Item: B
Item: C
Item: A
Item: B
Item: C
Methods and Properties of a C# Queue
Commonly used methods of a Queue are:
| Method | Description |
|---|---|
| Clear | Removes all the items from a Queue. |
| Contains | Determines whether an item is present in a Queue. |
| Peek | Gets the first item present in the beginning of a Queue without removing it. |
| Enqueue | Adds an item to the end of a Queue. |
| Dequeue | Removes the first item present in the beginning of a Queue. |
Commonly used properties of a Queue are:
| Property | Description |
|---|---|
| Count | Returns the number of items present in a Queue. |
No comments:
Post a Comment