Read the syntax
Materialise a dictionary with explicit selectors and a deliberate duplicate-key policy.
The chosen comparer supports this domain’s case-insensitive IDs.
What it is and why to use it
A list is convenient for traversal, but repeated lookup by a unique ID is better represented by a dictionary. ToDictionary enumerates a source immediately and creates one key/value entry per selected key. It is appropriate when uniqueness is an actual input invariant, not when duplicate rows must be silently discarded.
How it works
Choose the key selector, value selector and optional equality comparer. Duplicate keys under that comparer cause ArgumentException. Null reference keys are invalid. Materialisation copies the mapping but does not deep-clone referenced values. If multiple values belong to each key, use ToLookup or a grouped structure instead.
Common mistakes and limitations
Do not assume ToDictionary chooses the last duplicate automatically. Do not conceal conflicting records with an arbitrary first-wins rule unless the domain defines that policy. A comparer that ignores case can turn apparently different strings into duplicate keys.
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 byId = items.ToDictionary(item => item.Id, item => item.Name);Examples
Build a comparer-aware language lookup
Project small records into a map of IDs to display names.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var items = new[] { (Id: "php", Name: "PHP"), (Id: "cs", Name: "C#") };
var names = items.ToDictionary(item => item.Id, item => item.Name, StringComparer.OrdinalIgnoreCase);
Console.WriteLine(names["PHP"]);
Console.WriteLine(names["cs"]);
- The first selector supplies dictionary keys and the second supplies values.
- The chosen comparer supports this domain’s case-insensitive IDs.
- Queries use direct key lookup without depending on enumeration order.
- Expected output: PHP C#
- Validate uniqueness before relying on a dictionary representation.
Handle conflicting keys explicitly
Demonstrate a failed conversion rather than silently losing a record.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
var items = new[] { (Id: 1, Name: "First"), (Id: 1, Name: "Second") };
try {
var names = items.ToDictionary(item => item.Id, item => item.Name);
Console.WriteLine(names.Count);
} catch (ArgumentException) {
Console.WriteLine("Duplicate ID");
}
- Both rows select the same integer key.
- ToDictionary rejects the second equivalent key while enumerating the source.
- The controlled catch makes the invalid invariant visible. A real import would identify the conflicting records and apply an explicit resolution policy.
- Expected output: Duplicate ID
- Validate uniqueness before relying on a dictionary representation.
Best practices
- Validate uniqueness before relying on a dictionary representation.
- Use grouping for one-to-many data rather than overwriting it accidentally.
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