Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

LINQ ToList(), ToArray() and ToDictionary() methods

Reference for LINQ ToList, ToArray, ToDictionary and ToHashSet in C#: forcing execution, snapshots, duplicate-key errors, comparers and performance.

Most LINQ operators are lazy: they describe a query and run it when you enumerate. ToList(), ToArray() and ToDictionary() end that laziness. They run the query immediately and copy the results into a new collection, giving you a snapshot you can index, count, modify or enumerate repeatedly.

Use them to avoid re-running an expensive query, to freeze a result before the source changes, to get random access, or to release a database connection or file before it is disposed. ToDictionary() also builds a key lookup and throws if two elements produce the same key.

C#
List<int> list = query.ToList();
int[] array = query.ToArray();
var byId = users.ToDictionary(u => u.Id);

Try it

C# Snapshots and deferred execution

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.

C# ToDictionary and duplicate keys

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.

Syntax

C#
public static List<T> ToList<T>(this IEnumerable<T> source);
public static T[] ToArray<T>(this IEnumerable<T> source);
public static Dictionary<TKey, T> ToDictionary<T, TKey>(
    this IEnumerable<T> source, Func<T, TKey> keySelector) where TKey : notnull;
public static Dictionary<TKey, TElement> ToDictionary<T, TKey, TElement>(
    this IEnumerable<T> source, Func<T, TKey> keySelector, Func<T, TElement> elementSelector)
    where TKey : notnull;
// Overloads with IEqualityComparer<TKey>? exist for both ToDictionary forms
Name Description
keySelector Computes the dictionary key for each element.
elementSelector Computes the stored value. Without it the element itself is stored.
comparer Optional key equality, for example StringComparer.OrdinalIgnoreCase.

Returns: a new List<T>, array or Dictionary<TKey, T>. The call runs immediately.

Errors: ArgumentNullException for a null source, selector, or a null key. ArgumentException when two elements produce equal keys.

Usage notes

  • Eager vs lazy: the result does not change when the source changes afterwards. That is the point of a snapshot, and also the cause of stale data if you forget.
  • Copying cost: O(n) time and memory. ToArray() and ToList() avoid extra growth when the source reports its size (arrays, lists), otherwise they grow as they read.
  • ToList() vs ToArray(): use a list when you will add or remove items, an array when the size is final. Both support indexing.
  • Returned collections are mutable, and the elements themselves are not cloned: a list of objects is a list of the same references.
  • Duplicate keys throw. If duplicates are possible, group first, take First() per group, or use ToLookup(), which allows many values per key.
  • Don't call them in the middle of a query without reason. query.ToList().Where(...) in a database query pulls everything into memory before filtering.
  • Repeated enumeration: store the result once and reuse it instead of enumerating a deferred query several times.
  • Related converters: ToHashSet(), ToLookup(), and AsEnumerable() (which does not copy).
  • Dictionary ordering is not part of the contract. Sort the keys before printing if the output order matters.