Read the syntax
Materialise grouped lookup data and distinguish it from a deferred GroupBy query.
The comparer lets WEB address the web group.
What it is and why to use it
Repeatedly finding all lessons in a category can be easier with an index from category to many values. ToLookup materialises that structure immediately. Unlike a dictionary to one value, it naturally stores several elements under a key. Accessing an absent key gives an empty sequence rather than a missing-key exception.
How it works
Supply a key selector, an optional element selector and optionally a comparer. The source is enumerated when ToLookup runs. Later changes to the source collection do not add entries to that lookup, although referenced mutable elements may still be shared. GroupBy normally defers enumeration instead, so it can observe source changes when later enumerated.
Common mistakes and limitations
Do not treat ToLookup as a live view or as a deeply immutable copy. Materialising an unbounded source is not safe. Choose it when repeated key-based grouping lookups justify its storage cost rather than rebuilding it for each access.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
var lookup = items.ToLookup(item => item.Category, item => item.Name);Examples
Index titles by category
Use a comparer and read both present and absent groups.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var items = new[] { (Category: "web", Title: "HTML"), (Category: "web", Title: "CSS") };
var lookup = items.ToLookup(x => x.Category, x => x.Title, StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(", ", lookup["WEB"]));
Console.WriteLine(lookup["missing"].Count());
- The element selector stores each title beneath its category key.
- The comparer lets WEB address the web group.
- A missing group enumerates zero elements; it does not produce a null group or an indexer exception.
- Expected output: HTML, CSS 0
- Materialise once when repeated grouped lookup is required.
Observe immediate materialisation
Change the source after creating a lookup.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var source = new List<int> { 1, 2 };
var lookup = source.ToLookup(value => value % 2);
source.Add(3);
Console.WriteLine(string.Join(", ", lookup[1]));
Console.WriteLine(source.GroupBy(value => value % 2).Single(group => group.Key == 1).Count());
- ToLookup already enumerated the original two values.
- Adding 3 does not add it to the existing odd-key group.
- The newly enumerated GroupBy query sees both odd values in the current source, demonstrating a different execution time.
- Expected output: 1 2
- Materialise once when repeated grouped lookup is required.
Best practices
- Materialise once when repeated grouped lookup is required.
- Distinguish structural snapshots from shared mutable elements.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference