Collections in C#
C# includes varies classes that store the values or objects are called collections.
There are two types of collections available in C#:
- Non-generic collections
- Generic collections
The System.Collections namespace contains the non-generic collection types and System.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use the generic collections because they perform faster than non-generic collections and also minimize exceptions by giving compile-time errors.
Non-generic Collections
- Arraylist
- Stack
- Queue
- Hashtable
Queue in C#
Create a Queue in C#
To create Queue<T> in C#, we need to use the System.Collection.Generic namespace.
Queue<dataType> queueName = new Queue<dataType>();
Here, dataType indicates the queue's type. For example.
// create integer type stack
Queue<int> queue1 = new Queue<int>();
// create string type stack
Queue<string> queue2 = new Queue<string>();
Example
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a queue
Queue<string> fruits = new Queue<string>();
// adds "Apple" and "Orange" to the queue
fruits.Enqueue("Apple");
fruits.Enqueue("Orange");
// print elements of the queue
foreach (string item in fruits)
{
Console.WriteLine(item);
}
}
}
C# Queue Methods
C# provides 3 major Queue<T> methods. These methods are:
- Enqueue():
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a queue
Queue<int> numbers = new Queue<int>();
// adds 65 and 17 to the queue
numbers.Enqueue(65);
numbers.Enqueue(17);
// print elements of the queue
foreach (int item in numbers)
{
Console.WriteLine(item);
}
}
}
- Dequeue(): removes and returns an element from the beginning of the queue.
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a queue
Queue<string> colors = new Queue<string>();
// adds "Red" and "Blue" to the queue
colors.Enqueue("Red");
colors.Enqueue("Blue");
// removes element from the beginning of the colors queue
var removedElement = colors.Dequeue();
Console.WriteLine("Removed Element: " + removedElement);
}
}
- Peek(): returns an element from the beginning of the queue without removing it.
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a queue
Queue<string> planet = new Queue<string>();
// adds "Earth" and "Jupiter" to the queue
planet.Enqueue("Earth");
planet.Enqueue("Jupiter");
// returns element from the beginning of the planet queue
Console.WriteLine("Element at beginning of queue: " + planet.Peek());
}
}
Happy Coding!
Thanks.