Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

LINQ ToLookup() method

Reference for LINQ ToLookup() and ILookup in C#: one key with many values, missing keys, comparers, immutability and how it differs from GroupBy.

ToLookup() builds an ILookup<TKey, TElement>: a read-only collection that maps each key to a sequence of values, a multi-map. It runs immediately and groups the source once, so afterwards you get any key's values in constant time with the indexer.

It is like ToDictionary() for cases where keys repeat, and like GroupBy() when you need fast repeated access by key rather than a one-time pass. Looking up a missing key does not throw; it returns an empty sequence.

C#
var byCity = people.ToLookup(p => p.City);
foreach (var p in byCity["Oslo"]) { }

Try it

C# Looking up by key

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# Snapshot semantics and a join replacement

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 ILookup<TKey, TSource> ToLookup<TSource, TKey>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
    this IEnumerable<TSource> source, Func<TSource, TKey> keySelector,
    Func<TSource, TElement> elementSelector);
// plus overloads with IEqualityComparer<TKey>?

public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
{
    int Count { get; }
    IEnumerable<TElement> this[TKey key] { get; }
    bool Contains(TKey key);
}
Name Description
keySelector Computes the key of each element.
elementSelector Optional. Chooses the value stored for each element.
comparer Optional key equality.
Count The number of distinct keys (not elements).

Returns: an ILookup<TKey, TElement>. The query runs immediately.

Errors: ArgumentNullException for a null source or selector. Duplicate keys are expected and fine.

Usage notes

  • Missing key = empty sequence. There is no KeyNotFoundException, so you can write lookup[id].Sum(...) without a check.
  • Immutable. There is no Add() or Remove(). Build a new lookup, or use Dictionary<TKey, List<T>> when you need to change it.
  • Order: keys enumerate in order of first appearance, and the values of a key keep their source order.
  • Null keys are permitted, which a Dictionary does not allow.
  • ToLookup() vs GroupBy(): both group, but ToLookup() is eager and indexed; GroupBy() is deferred and has no key indexer. Pick ToLookup() when you will read several keys, GroupBy() for a single streaming pass.
  • ToLookup() vs ToDictionary(): a dictionary throws on duplicate keys and returns one value per key.
  • Performance: building is O(n); each lookup is O(1) on average. It replaces a nested loop or repeated Where() filters with a single pass over each side.
  • Memory: it holds all elements, so use an element selector to store only what you need.
  • Joins: Join() and GroupJoin() build a lookup internally for the inner side.