C# - Data Structures
C# offers a variety of data structures, both built-in and from the System.Collections
and System.Collections.Generic
namespaces. These data structures are used to store and manage data efficiently. Below are some commonly used C# data structures:
1. Arrays
Arrays are the simplest type of data structure in C#. They are used to store a fixed-size sequential collection of elements of the same type.
csharpint[] numbers = new int[5] {1, 2, 3, 4, 5};
Key Features:
- Fixed size.
- Zero-based indexing.
- Access time: O(1).
2. Lists (List<T>)
List<T>
is a dynamic array that can grow and shrink as needed. It's part of System.Collections.Generic
.
csharpList<int> numbers = new List<int> {1, 2, 3, 4, 5};
numbers.Add(6);
numbers.Remove(2);
Key Features:
- Dynamic size.
- Zero-based indexing.
- Access time: O(1) for accessing elements by index.
3. LinkedList<T>
A LinkedList<T>
is a doubly linked list, allowing traversal in both directions. It's part of System.Collections.Generic
.
csharpLinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(1);
numbers.AddLast(2);
numbers.AddFirst(0);
Key Features:
- Efficient insertions and deletions at any point.
- Linear traversal time: O(n).
4. Stack (Stack<T>)
Stack<T>
is a last-in, first-out (LIFO) data structure. It's part of System.Collections.Generic
.
csharpStack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int top = stack.Pop();
Key Features:
- LIFO structure.
- Push and pop operations: O(1).
5. Queue (Queue<T>)
Queue<T>
is a first-in, first-out (FIFO) data structure. It's part of System.Collections.Generic
.
csharpQueue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
int front = queue.Dequeue();
Key Features:
- FIFO structure.
- Enqueue and dequeue operations: O(1).
6. Dictionary (Dictionary<TKey, TValue>)
Dictionary<TKey, TValue>
is a collection of key-value pairs. It's part of System.Collections.Generic
.
csharpDictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("John", 30);
ages["Jane"] = 25;
int age = ages["John"];
Key Features:
- Key-value pairs.
- Fast lookups: O(1) on average.
- Keys must be unique.
7. HashSet (HashSet<T>)
HashSet<T>
is a collection that contains no duplicate elements. It’s part of System.Collections.Generic
.
csharpHashSet<int> uniqueNumbers = new HashSet<int> {1, 2, 3, 3};
uniqueNumbers.Add(4);
Key Features:
- No duplicate elements.
- Fast lookups: O(1) on average.
8. SortedList (SortedList<TKey, TValue>)
SortedList<TKey, TValue>
stores key-value pairs, sorted by the key.
csharpSortedList<string, int> sortedAges = new SortedList<string, int>();
sortedAges.Add("John", 30);
sortedAges.Add("Jane", 25);
Key Features:
- Sorted by keys.
- Fast lookups: O(log n).
- Fast insertions and deletions: O(log n).
9. SortedDictionary (SortedDictionary<TKey, TValue>)
Similar to SortedList
, but optimized for fast insertions and deletions.
csharpSortedDictionary<string, int> sortedAges = new SortedDictionary<string, int>();
sortedAges.Add("John", 30);
sortedAges.Add("Jane", 25);
Key Features:
- Sorted by keys.
- Fast lookups: O(log n).
- More efficient than
SortedList
for frequent insertions and deletions.
10. SortedSet (SortedSet<T>)
A SortedSet<T>
is a set that maintains its elements in a sorted order.
csharpSortedSet<int> sortedSet = new SortedSet<int> {1, 3, 2, 5};
Key Features:
- Sorted set with unique elements.
- O(log n) for add, remove, and search.
11. Concurrent Collections
C# provides thread-safe data structures in the System.Collections.Concurrent
namespace. Examples include:
ConcurrentDictionary<TKey, TValue>
BlockingCollection<T>
ConcurrentQueue<T>
ConcurrentStack<T>
These collections allow safe access to data across multiple threads without requiring additional locking.
12. Tuple
Tuples allow you to store multiple items of different types in a single object.
csharpTuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "Hello", true);
Console.WriteLine(tuple.Item1); // Output: 1
Key Features:
- Store multiple values.
- Immutable.
13. Custom Data Structures
You can also create your own custom data structures by defining classes or structs in C#.
csharppublic class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
Example of a custom linked list:
csharppublic class CustomLinkedList
{
public Node Head;
public void Add(int data)
{
if (Head == null)
{
Head = new Node(data);
}
else
{
Node current = Head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = new Node(data);
}
}
}
Summary
- Array: Fixed size, fast access.
- List<T>: Dynamic size, fast access.
- LinkedList<T>: Efficient for insertions and deletions.
- Stack<T>: LIFO.
- Queue<T>: FIFO.
- Dictionary<TKey, TValue>: Key-value pairs, fast lookups.
- HashSet<T>: Unique elements.
- SortedList<TKey, TValue> / SortedDictionary<TKey, TValue>: Sorted key-value pairs.
- Concurrent Collections: Thread-safe data structures.
- Tuple: Multiple values of different types.
These data structures are the foundation for many algorithms and applications in C#. The choice of data structure depends on the specific requirements of your task, such as access time, memory usage, and the need for sorting or uniqueness.