Collections in C#: List, Dictionary, HashSet and Queue
C# collections let you store and work with groups of values. Choosing the right collection can make code simpler, clearer, and faster.
List<T>
List<T> is the general-purpose choice when you need an ordered, dynamically sized collection.
var names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("Diana");
foreach (var name in names)
{
Console.WriteLine(name);
}
Use a list when you frequently access items by index or need to preserve insertion order.
Dictionary<TKey, TValue>
A dictionary stores values by a key and is useful for fast lookups.
var employees = new Dictionary<int, string>
{
[1001] = "Alice",
[1002] = "Bob"
};
if (employees.TryGetValue(1002, out var name))
{
Console.WriteLine(name);
}
TryGetValue is usually preferable to indexing when the key might not exist.
HashSet<T>
A HashSet<T> stores unique values and is useful when fast membership checks matter.
var tags = new HashSet<string> { "csharp", "dotnet" };
tags.Add("csharp");
Console.WriteLine(tags.Count);
Adding an existing value does not create a duplicate.
Queue<T>
A queue follows first-in, first-out (FIFO) behavior.
var queue = new Queue<string>();
queue.Enqueue("Task 1");
queue.Enqueue("Task 2");
var next = queue.Dequeue();
Queues are useful for work items, processing pipelines, and other FIFO scenarios.
Stack<T>
A stack follows last-in, first-out (LIFO) behavior.
var stack = new Stack<string>();
stack.Push("Page A");
stack.Push("Page B");
var current = stack.Pop();
Which Collection Should You Choose?
| Collection | Typical use |
|---|---|
| List<T> | Ordered general-purpose data |
| Dictionary<TKey,TValue> | Key-based lookup |
| HashSet<T> | Unique values and membership checks |
| Queue<T> | FIFO processing |
| Stack<T> | LIFO processing |
Common Mistakes
- Using a list when lookups should be key-based.
- Assuming a dictionary preserves the semantics of a list.
- Using a list to enforce uniqueness instead of a hash set.
- Calling
DequeueorPopwithout checking whether the collection contains an item. - Choosing a collection without considering access patterns.
Summary
Start with List<T> for ordinary ordered data, use Dictionary<TKey,TValue> for key lookups, HashSet<T> for uniqueness, Queue<T> for FIFO processing, and Stack<T> for LIFO behavior.
Continue Learning C#
See the C# Tutorials pillar for the complete roadmap and related guides.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.