In C#, collections are a group of objects or data structures that are used to store, manage, and manipulate data efficiently. Collections can hold different types of data, and they provide methods for adding, removing, searching, sorting, and iterating over the data.
There are many types of Collection
1. Array
Arrays are a collection of elements of the same type, stored in contiguous memory locations. They have a fixed size, meaning once an array is created, its size cannot be changed.
Syntax:
int[] numbers = { 5, 10, 15, 20, 25 };
2. Generic Collections (System.Collections.Generic)
Generic collections provide type safety by allowing only elements of a specific type to be stored. They are more efficient compared to non-generic collections because they eliminate the need for type casting.
There are many types of Generic Collection
List<T>:
1. A dynamically sized collection that allows adding, removing, and accessing elements by index.
2. It can store any type of element (T represents the type).
Example:
List numbers = new List { 5, 10, 15, 20, 25 };
numbers.Add(30); // Adding an element
numbers.Remove(10); // Removing an element
- Add(T item): Adds an element to the list.
- Remove(T item): Removes the first occurrence of the element.
Dictionary<TKey, TValue>
1. A collection of key-value pairs, where each key is unique.
2. Efficient lookup, insertion, and deletion based on keys.
Example:
Dictionary employee = new Dictionary
{
{ "John", 35 },
{ "Tom", 30 }
};
employee["John"] = 40; // Adding/Updating an element
Methods
- Add(TKey key, TValue value): Adds a new key-value pair.
- ContainsKey(TKey key): Checks if the dictionary contains a key.
- TryGetValue(TKey key, out TValue value): Tries to get a value for a key.
- Remove(TKey key): Removes a key-value pair by key.
Queue<T>
1. A First-In-First-Out (FIFO) collection.
2. Elements are added at the rear (enqueue) and removed from the front (dequeue).
Example:
Queue queue = new Queue();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
int first = queue.Dequeue(); // Removes and returns the first element (1)
Methods
- Enqueue(T item): Adds an item to the end of the queue.
- Dequeue(): Removes and returns the first item.
- Peek(): Returns the first element without removing it.
Stack<T>
1. A Last-In-First-Out (LIFO) collection.
2. Elements are added and removed from the top.
Example:
Stack stack = new Stack();
stack.Push(1); // Adds an element to the top
stack.Push(2);
stack.Push(3);
int top = stack.Pop(); // Removes and returns the top element (3)
Methods:
- Push(T item): Adds an item to the top of the stack.
- Pop(): Removes and returns the top item.
- Peek(): Returns the top item without removing it.
3. Non-Generic Collections (System.Collections)
Non-generic collections store elements of any data type (usually Object). These collections provide more flexibility but at the cost of type safety, meaning you’ll need to use casting when accessing elements.
There are many types of Non-Generic Collections
ArrayList
1. Similar to a List<T>, but non-generic, so it can store any type of object.
2. Provides dynamic resizing.
Example:
ArrayList list = new ArrayList();
list.Add(35);
list.Add("John");
list.Add(true);
Methods
- Add(object value): Adds an element to the list.
- Remove(object value): Removes the first occurrence of the element.
- Insert(int index, object value): Inserts an element at a specific index.
Hashtable
1. A collection of key-value pairs similar to Dictionary<TKey, TValue>, but it is non-generic and can store keys and values of any type.
2. The keys are hashed to ensure fast lookup.
Example:
Hashtable hashtable = new Hashtable();
hashtable.Add("John", 35);
hashtable.Add("Tom", 30);
Methods
- Add(object key, object value): Adds a key-value pair.
- Remove(object key): Removes a key-value pair.
- ContainsKey(object key): Checks if the key exists.
SortedList
1. A collection of key-value pairs that are automatically sorted by the keys.
2. Works similarly to a Hashtable but maintains the elements in sorted order.
Example:
SortedList sortedList = new SortedList();
sortedList.Add("John", 35);
sortedList.Add("Tom", 30);
Methods
- Add(object key, object value): Adds a key-value pair.
- Remove(object key): Removes a key-value pair.
- ContainsKey(object key): Checks if the key exists.
4. Concurrent Collections (System.Collections.Concurrent)
Concurrent collections are specifically designed for multi-threaded environments where threads are accessing or modifying the collection concurrently. These collections ensure thread safety without needing explicit locks.
Types of Concurrent Collections:
ConcurrentDictionary<TKey, TValue>
1. A thread-safe version of Dictionary<TKey, TValue>.
2. Supports atomic operations for adding, removing, and updating key-value pairs.
Example:
ConcurrentDictionary dict = new ConcurrentDictionary();
dict.TryAdd("John", 35);
dict["Tom"] = 30; // Adding/updating an entry
Methods
- TryAdd(TKey key, TValue value): Attempts to add a new key-value pair.
- TryUpdate(TKey key, TValue newValue, TValue comparisonValue): Updates a value if it matches a specified comparison value.
- GetOrAdd(TKey key, TValue value): Adds the value if the key does not exist.
ConcurrentQueue<T>
1. A thread-safe FIFO collection.
2. Allows multiple threads to enqueue and dequeue items safely.
Example:
ConcurrentQueue queue = new ConcurrentQueue();
queue.Enqueue(10);
queue.Enqueue(20);
Methods
- Enqueue(T item): Adds an item to the end of the queue.
- TryDequeue(out T result): Removes and returns the first item safely.
ConcurrentStack<T>
1. A thread-safe LIFO collection.
2. Allows multiple threads to push and pop items safely.
Example:
ConcurrentStack stack = new ConcurrentStack();
stack.Push(10);
stack.Push(20);
Methods
- Push(T item): Adds an item to the top of the stack.
- TryPop(out T result): Removes and returns the top item safely.