Sequential Lists such as Queue and Stack in .NET Framework

Sometimes you don’t require complicated list such as ArraysList and only need to store and retrieve data in some sort of sequential order. There are two methods known one is called FIFO and another is called LIFO.

Queue is FIFO with the following properties and methods

Properties

 

NameDescription
Count Gets the number of items in the queue collection

Methods

 

NameDescription
Dequeue Retrieves an item from the front of the queue
Enqueue Adds an item to the end of the queue
Peek Retrieves the first item from the queue without removing

With queue we can add duplicate as well we null values so it has to be taking into consideration when working with the queue. In order for us to see if queue is empty it’s not enough just to Peek we need to use Count property.

Queue myQ = new Queue();
myQ.Enqueue("First Item");
myQ.Enqueue("Second Item");
while (myQ.Count > 0)
{
    Console.WriteLine(myQ.Dequeue());
}

 

Stack is LIFO where we first push item and then we pop item from the stack. By default stock capacity is set to be 10.

Properties

 

NameDescription
Count Determines the number of items in the stack

Methods

 

NameDescription
Pop Retrieves an item from the top of the stackby removing it
Push Adds an item to the top of the stack
Peek Retrieves the top item from the stack without removing it

Stack myS = new Stack();
myS.Push("First Item");
myS.Push("Second Item");
while (myS.Count > 0)
{
    Console.WriteLine(myS.Pop());
}