C# Collections
Objectives
- What is Collections?
- Lists
- Arrays vs Lists
- Dictionaries
- Sets
- Queues
- Stacks
What is Collections?
Collections are objects that pack many other elements into one.
They give a way of organizing, storing and handling data in an efficient manner.
C# provides a rich set of collection classes in the .NET Framework that offer various data structures and algorithms for working with collections.
Lists:
The list is akin to a dynamic array whose size can change during runtime either by shrinking or expanding it dynamically.
This feature allows them to add, remove, or modify items rapidly according to their index positions.
using System.Collections.Generic;
List numbers = new List();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Arrays vs Lists:
List: Unlike lists that can be resized at any time during execution due to their flexibility,
Arrays: have fixed sizes declared once before any uses leading to its declaration earlier on completion which cannot change for a running code.
Dictionaries:
A dictionary is a collection that stores key-value pairs.
They make searching fast as they use keys and also support removing and adding key-value pairs.
using System.Collections.Generic;
Dictionary ages = new Dictionary();
ages["John"] = 30;
ages["Alice"] = 25;
Console.WriteLine("John's age: " + ages["John"]);
Sets:
The 'Sets' are collections that store unique elements without duplicates.
Among them, there is one type of operation for the set such as a union, an intersection and a difference.
using System.Collections.Generic;
HashSet numbers = new HashSet();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(1); // Duplicate elements are ignored
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Queues:
The 'Queues' follow the principle First-In-First-Out (FIFO).
They allow adding (enqueue) and removing items from the front (dequeue), respectively.
using System.Collections.Generic;
Queue queue = new Queue();
queue.Enqueue("Apple");
queue.Enqueue("Banana");
queue.Enqueue("Orange");
while (queue.Count > 0)
{
Console.WriteLine(queue.Dequeue());
}
Stacks:
‘Stacks’ follow the principle Last-In-First-Out (LIFO).
They allow for addition of an element to the stack’s top(push) or removal of an element from stack’s top(pop).
Example:
using System.Collections.Generic;
Stack stack = new Stack();
stack.Push("Apple");
stack.Push("Banana");
stack.Push("Orange");
while (stack.Count > 0)
{
Console.WriteLine(stack.Pop());
}