Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 182 ยท Collections

List of T

Learn C# List<T> - creating, Add, Insert, Remove, RemoveAll, IndexOf, Contains, Sort with Comparison, capacity growth, performance costs and common pitfalls.

An array has a fixed length, but most real data does not: a shopping cart gets items added and removed, a log collects lines, a search returns however many results it finds. List<T> is the standard growable sequence in .NET. The T stands for the element type, so List<string> is a list of strings and List<int> a list of integers. It is the collection you will use more than any other.

A list gives you an array's fast numbered access plus methods to add, insert, remove, find and sort. This lesson shows how to use those methods, how the list grows internally (and why that matters for performance), how to sort with custom rules, which operations are cheap or costly, and a few traps such as changing a list while looping over it.

Creating a list and adding items

C# Creating and filling a list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The number of items is Count (a property, unlike an array's Length). The indexer works like an array's, and an invalid index throws ArgumentOutOfRangeException (the last line of the example prints Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')).

Insert, remove, find

C# Insert, Remove, IndexOf, Contains

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Remove(value) deletes the first element equal to value and returns whether it found one. RemoveAt(index) is for when you already know the position. After any insertion or removal in the middle, the elements after it shift by one position, so indices change.

Find with conditions: Find, Exists, FindAll, RemoveAll

List<T> has methods that take a lambda describing the condition:

C# Searching and removing with predicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Find returns default(T) when nothing matches (0 for int, null for a reference type), which can be confused with a real value. When that matters, use FindIndex (returns -1) or Exists. RemoveAll is the right way to remove many items in one go: it is a single pass, whereas calling Remove in a loop shifts items over and over.

Looping over a list

Use foreach to read. It is not allowed to add or remove items while a foreach is running over the same list:

C# Modifying a list during foreach (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

After the first iteration the next step throws System.InvalidOperationException: Collection was modified; enumeration operation may not execute. The list keeps an internal version number, and the enumerator checks it on each step. To remove items while looping, use RemoveAll, loop over a copy (foreach (var n in names.ToList())), or loop backwards with a for:

C# Safe removal while looping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Going backwards works because removing the item at i only shifts items you have already visited.

Sorting

Sort() orders a list in place using the element type's default comparison (numbers ascending, strings by ordinal comparison). Pass a Comparison<T> lambda for custom rules: it receives two items and returns a negative number if the first comes first, zero if equal, positive if the second comes first.

C# Sort and Sort with Comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The default sort of strings is ordinal, so uppercase letters sort before lowercase ones ("Fig" comes before "apple"). List<T>.Sort is not stable: items that compare equal can end up in any order relative to each other. When you need stability, use LINQ's OrderBy (sorted collections explains the differences). Always include a tie-breaker in your comparison, as the example does with the name.

Capacity: how a list grows

Inside, a List<T> holds an array. Count is how many slots are in use; Capacity is how long that internal array is. When you add an item and the array is full, the list allocates a new array twice as big (starting at 4; a new empty list has capacity 0), copies the items and discards the old array. We can watch it happen:

C# Watching Capacity grow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Doubling makes Add amortized O(1): an occasional expensive copy, but cheap on average. If you know roughly how many items are coming, pass the size to the constructor (or set Capacity, or use EnsureCapacity) to avoid the repeated copying. TrimExcess gives back unused slots, rarely needed.

What each operation costs

Operation Cost Note
list[i], Count O(1) Direct array access
Add(x) at end O(1) amortized O(n) on the rare growth step
Insert(i, x) / RemoveAt(i) O(n) Shifts the items after i
Remove(x), IndexOf(x), Contains(x) O(n) Linear search
Sort() O(n log n) Introspective sort
BinarySearch(x) O(log n) Only on a sorted list

The line that surprises beginners: Contains on a big list in a loop is O(n) each time, so checking 100,000 items against a 100,000-item list takes billions of comparisons. Use a HashSet or Dictionary for fast membership tests. Removing from the front of a list (RemoveAt(0)) is also O(n); if you need a queue, use Queue<T> (Stack, Queue, LinkedList).

Lists hold references, not copies

For classes, a list stores references to objects. Two lists can contain the same objects, and changing an object through one list changes it everywhere:

C# Shared objects in two lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

new List<T>(existing) makes a shallow copy: a separate list, but the same element objects. If the element type is a struct, each element is copied by value instead.

Advanced preview: Span and CollectionsMarshal

For performance-critical code, .NET lets you look directly at a list's internal array. CollectionsMarshal.AsSpan(list) returns a Span<T> over the live items, so you can read and write them without copying or the version check:

C# A Span over a list (advanced)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This is an expert tool: never add or remove items while you hold the span, because the list may reallocate and the span would then point at a stale array. For everyday code use the normal indexer and methods.

Common mistakes

  • Using Length instead of Count on a list (and Count() as a method on an array).
  • Modifying the list inside foreach. Use RemoveAll, a backwards for, or iterate a copy.
  • Assuming Find signals "not found" clearly. For value types it returns 0.
  • Sorting by subtraction ((a, b) => a - b) breaks on overflow; use CompareTo.
  • Calling Contains repeatedly on huge lists: switch to a set.
  • Removing from the front in a loop; use a Queue<T>.
  • Forgetting that the list holds references, so a "copy" may share objects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Count property of a List<T> tell you?

    Count is the number of stored items. Capacity is the size of the internal array, which is usually larger.
  2. 2. Why does Add on a List<T> run in amortized O(1) time?

    Most Add calls just write into free space. When the array is full, the list allocates one twice as large and copies once, which is spread out over many cheap adds.
  3. 3. What happens if you call names.Remove(name) inside a foreach loop over names?

    The enumerator detects that the collection changed and throws InvalidOperationException. Use RemoveAll or a backwards for loop.
  4. 4. Which call removes all negative numbers from List<int> data in a single pass?

    RemoveAll takes a predicate, removes every matching element and returns how many were removed.
  5. 5. Which operation is O(n) on a List<T>?

    Inserting at the front shifts every existing item one position. Index access, Count and a plain add at the end are constant time.

Summary

  • List<T> is a growable, strongly typed sequence: Add, Insert, Remove, RemoveAt, RemoveAll, IndexOf, Contains, Find, Sort.
  • Use Count, not Length; the indexer is fast, but out-of-range access throws.
  • Never modify a list inside foreach over it; use RemoveAll or a backwards for.
  • Sort(Comparison<T>) accepts a lambda; it is unstable, so add tie-breakers.
  • The internal array doubles when full, so Add is amortized O(1); pre-size with new List<T>(n) when you can.
  • Middle inserts/removals and searches are O(n); use sets or dictionaries for lookups.
  • Lists store references; copies are shallow.

Next: Dictionary of TKey, TValue