Lesson 17 of 24

In progress

Course progress

C# and .NET

Collections: List, Dictionary and friends

Choose the right collection, use a dictionary for lookup, and recognise the cost of adding to a list in a loop.

The collections library answers three questions: do I need order, uniqueness, or lookup by key? Pick by those, and most performance problems disappear before they exist.

What you will learn

  • Use List<T>, Dictionary<TKey,TValue>, HashSet<T> and Queue<T>.
  • Choose a collection by its access pattern.
  • Avoid the common costs.

List

var names = new List<string> { "Ana", "Ravi" };
names.Add("Meera");
names.Insert(1, "Sam");
names.Remove("Ravi");
names.Sort();
Console.WriteLine(names.Count);
Console.WriteLine(names[0]);
Console.WriteLine(names.Contains("Meera"));   // linear scan

A list is an ordered, resizable array. Indexing is fast; Contains, Remove and Insert in the middle are linear.

The backing array doubles when it fills, copying the existing elements. If the size is known, pass a capacity: new List<int>(capacity: 10_000). That is a real saving when adding a hundred thousand items one at a time, where the repeated copying would otherwise dominate the run time.

Dictionary

var stock = new Dictionary<string, int>
{
["pen"] = 40,
["book"] = 12
};
stock["lamp"] = 3;
if (stock.TryGetValue("book", out int books))
{
Console.WriteLine(books);
}
foreach (var (sku, count) in stock)
{
Console.WriteLine($"{sku}: {count}");
}

A dictionary maps unique keys to values with near-constant lookup. TryGetValue avoids both the exception from the indexer and the double lookup of ContainsKey followed by an index.

Indexing a missing key throws KeyNotFoundException. GetValueOrDefault returns a default instead, which is right when absence is normal.

Keys must have a stable Equals and GetHashCode. Strings, numbers and records are safe; a mutable class used as a key can become unreachable after a change.

Iteration order is unspecified in practice, though insertion order tends to hold until a removal. Use SortedDictionary when you need ordering by key.

HashSet

var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
seen.Add("Ana");
seen.Add("ana");
Console.WriteLine(seen.Count);   // 1

A set stores unique values and answers Contains quickly. It is the right structure for deduplication and membership tests.

The comparer is part of the set’s behaviour. OrdinalIgnoreCase makes "Ana" and "ana" the same entry, which is usually what you want for identifiers and rarely what you want for display names.

Queue and Stack

var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
Console.WriteLine(queue.Dequeue());   // first
var stack = new Stack<string>();
stack.Push("a");
stack.Push("b");
Console.WriteLine(stack.Pop());       // b

A queue is first-in, first-out; a stack is last-in, first-out. Both are O(1) at the working end, which makes them the right tools for breadth-first and depth-first traversal.

Choosing

Need Collection
Ordered sequence, index access List<T>
Lookup by key Dictionary<TKey,TValue>
Unique values, membership HashSet<T>
First in, first out Queue<T>
Last in, first out Stack<T>
Sorted keys SortedDictionary<TKey,TValue>

The wrong choice usually shows up as a scan hidden inside a loop. A List.Contains inside a loop over the same list is O(n²); a HashSet.Contains makes it O(n).

Read-only views

public IReadOnlyList<string> Names => names;

Returning an interface prevents a caller from mutating the collection while still allowing iteration. IReadOnlyList<T> is the right property type for a list you own; IEnumerable<T> is the right parameter type when you only need to walk it.

AsReadOnly() wraps a list in a ReadOnlyCollection that reflects changes; List<T>.Copy and ToArray produce independent copies. Choose based on whether the caller should see later updates.

Concurrent collections

ConcurrentDictionary and ConcurrentQueue are safe for multiple threads. They are slower per operation than the plain versions, so use them only when several threads actually share the collection. Most application code should keep a collection owned by one thread and pass messages instead.

A common performance trap

var names = new List<string>();
foreach (var id in ids)
{
if (!names.Contains(id.ToString())) names.Add(id.ToString());
}

That is quadratic. The set version is linear:

var seen = new HashSet<string>();
foreach (var id in ids)
{
seen.Add(id.ToString());
}

The same mistake appears with Any(x => x.Id == id) inside a loop, which a dictionary keyed by id fixes. Whenever a loop contains a search over the same data, a hash-based structure is usually the answer.

Modifying a Dictionary while iterating it. The enumerator throws InvalidOperationException. Collect the keys to change, then apply them after the loop.

Given a list of orders with a customer name and an amount, build a dictionary of totals per customer, then print the customers with more than one order.

Show solution
record Order(string Customer, decimal Amount); var orders = new List<Order> { new("Ana", 120m), new("Ravi", 80m), new("Ana", 90m) }; var totals = new Dictionary<string, (int count, decimal total)>(); foreach (var order in orders) { var current = totals.GetValueOrDefault(order.Customer); totals[order.Customer] = (current.count + 1, current.total + order.Amount); } foreach (var (name, info) in totals.Where(kv => kv.Value.count > 1)) { Console.WriteLine($"{name}: {info.count} orders, {info.total:F2}"); }

GetValueOrDefault returns a zero tuple for a new customer, so the update is one line without a branch. The tuple keeps the count and total together, which is what the report needs next to each name.

Recap

  • Choose by access pattern: list for order, dictionary for lookup, set for membership.
  • TryGetValue and GetValueOrDefault avoid exceptions and double lookups.
  • Return IReadOnlyList<T> or IEnumerable<T> so callers cannot mutate your state.

Next, LINQ: describing queries over collections.

Does Dictionary preserve insertion order?
Not as a contract. It happens to today, and relying on it is a bug waiting for a refactor.
List or array?
List when the size changes, array when it is fixed and small, or when an API needs one.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.