How to Turn a List into a Dictionary with LINQ ToDictionary in C#
countries.ToDictionary(country => country.Code, country => country.Name) turns a list into a Dictionary<string, string> in one line: the first function picks each item's key, the second its value. Then you can find any item by its key.
Microsoft's reference: Creates a Dictionary<TKey,TValue> from an IEnumerable<T> according to specified key selector and element selector functions. The key selector is A function to extract a key from each element. The element selector, which picks the value, is A transform function to produce a result element value from each element.
Why build a dictionary at all? Because finding an item in it by its key is quick. The Dictionary<TKey,TValue> reference: Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table. When your code keeps asking "which item has this code?", turn the list into a dictionary once and look items up by key.
Syntax
Dictionary<TKey, TValue> <dictionary> = <items>.ToDictionary(<item> => <key>, <item> => <value>);
Dictionary<TKey, TSource> <dictionary> = <items>.ToDictionary(<item> => <key>);
Dictionary<TKey, TValue> <dictionary> = <items>.ToDictionary(<item> => <key>, <item> => <value>, <comparer>);
| Part | What it is |
|---|---|
<items> | Any sequence, such as a List<T> or an array |
<item> => <key> | The key selector: it gets one item and returns its key, such as country => country.Code |
<item> => <value> | The value selector: it gets one item and returns the value to store. Leave it out, and each value is the whole item |
<comparer> | Optional: how keys are compared, such as StringComparer.OrdinalIgnoreCase to ignore upper and lower case |
TKey, TValue, TSource | The type of the keys, of the values, and of the items in the list |
The reference sets two rules for the keys: Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer. A key cannot be null, but a value can be, if its type TValue is a reference type.
The Example
A console app called LinqToDictionary has a list of three countries, each with a two-letter code, a name and a capital. It turns the list into a dictionary from code to name, and into a dictionary from code to the whole country, then looks entries up by code.
Prerequisites
- The .NET 10 SDK.
dotnet --versionprints a version that starts with10.0.
Step 1: Create a Console App
dotnet new console -n LinqToDictionary
cd LinqToDictionary
The template "Console App" was created successfully.
Processing post-creation actions...
Restoring /Users/you/source/LinqToDictionary/LinqToDictionary.csproj:
Determining projects to restore...
Restored /Users/you/source/LinqToDictionary/LinqToDictionary.csproj (in 46 ms).
Restore succeeded.
dotnet new console -n LinqToDictionary creates a folder named LinqToDictionary with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or LinqToDictionary.csproj in Visual Studio.
Step 2: Write the Code
Replace everything in Program.cs. First the list:
// A list of countries: a two-letter code, a name and a capital.
List<Country> countries =
[
new("FR", "France", "Paris"),
new("JP", "Japan", "Tokyo"),
new("KE", "Kenya", "Nairobi"),
];
Each new("FR", "France", "Paris") creates a Country, the record at the end of the file.
Then a dictionary from code to name:
// Key: each country's code. Value: its name.
Dictionary<string, string> namesByCode = countries.ToDictionary(country => country.Code, country => country.Name);
Console.WriteLine($"Entries: {namesByCode.Count}");
Console.WriteLine($"JP is {namesByCode["JP"]}");
country => country.Code is the key selector and country => country.Name the value selector. ToDictionary calls both for every country and stores the name under the code. namesByCode["JP"] then reads the value stored under the key JP.
Then a dictionary from code to the whole country:
// Key only: each value is the whole Country.
Dictionary<string, Country> countriesByCode = countries.ToDictionary(country => country.Code);
Console.WriteLine($"The capital of KE is {countriesByCode["KE"].Capital}");
With only a key selector, each value is the item itself, so countriesByCode["KE"] is a Country and .Capital reads its capital.
Last, every entry, and the record:
// Every entry: a key and its value.
foreach (KeyValuePair<string, string> entry in namesByCode)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
record Country(string Code, string Name, string Capital);
A foreach over a dictionary gives you one KeyValuePair<string, string> per entry: entry.Key is the code and entry.Value the name.
Step 3: Run It
Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:
dotnet run
Entries: 3
JP is Japan
The capital of KE is Nairobi
FR = France
JP = Japan
KE = Kenya

The dictionary has 3 entries, one per country, and namesByCode["JP"] found Japan by its code. With only a key selector, countriesByCode["KE"] returned the whole Kenya record, so .Capital gave Nairobi. The loop printed each code with its name.
The Complete File

// A list of countries: a two-letter code, a name and a capital.
List<Country> countries =
[
new("FR", "France", "Paris"),
new("JP", "Japan", "Tokyo"),
new("KE", "Kenya", "Nairobi"),
];
// Key: each country's code. Value: its name.
Dictionary<string, string> namesByCode = countries.ToDictionary(country => country.Code, country => country.Name);
Console.WriteLine($"Entries: {namesByCode.Count}");
Console.WriteLine($"JP is {namesByCode["JP"]}");
// Key only: each value is the whole Country.
Dictionary<string, Country> countriesByCode = countries.ToDictionary(country => country.Code);
Console.WriteLine($"The capital of KE is {countriesByCode["KE"].Capital}");
// Every entry: a key and its value.
foreach (KeyValuePair<string, string> entry in namesByCode)
{
Console.WriteLine($"{entry.Key} = {entry.Value}");
}
record Country(string Code, string Name, string Capital);
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Two items with the same key | A list with two FR countries threw Unhandled exception. System.ArgumentException: An item with the same key has already been added. Key: FR | Make sure every key is different. To keep the first item for each key, call DistinctBy first: countries.DistinctBy(country => country.Code).ToDictionary(...) printed Entries: 2 and FR is France |
| Looking a key up in a different case | namesByCode["jp"] threw System.Collections.Generic.KeyNotFoundException: The given key 'jp' was not present in the dictionary., because the stored key is JP, not jp | Pass a comparer as the third argument: with StringComparer.OrdinalIgnoreCase, namesByCode["jp"] printed jp is Japan |
A key that can be null | With string? Code, the build warned warning CS8714: The type 'string?' cannot be used as type parameter 'TKey' in the generic type or method 'Enumerable.ToDictionary<TSource, TKey, TElement>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint., and a country without a code then threw System.ArgumentNullException: Value cannot be null. (Parameter 'key') | Give every item a key before you build the dictionary. The reference lists this case: keySelector produces a key that is null. |
FAQ
Does the dictionary keep the order of the list?
Don't count on it. The run printed FR, JP and KE in the list's order, but the reference says: The order in which the items are returned is undefined. When the order matters, loop over the list, and use the dictionary only to look items up.
What if several items share a key?
Call ToLookup instead. It takes the same key and value selectors, and the reference says it returns a one-to-many dictionary that maps keys to collections of values. A Lookup<TKey,TElement> differs from a Dictionary<TKey,TValue>, which performs a one-to-one mapping of keys to single values. Here France and French Guiana both have the code FR:
List<Country> countries =
[
new("FR", "France", "Paris"),
new("JP", "Japan", "Tokyo"),
new("FR", "French Guiana", "Cayenne"),
];
ILookup<string, string> namesByCode = countries.ToLookup(country => country.Code, country => country.Name);
Console.WriteLine($"Keys: {namesByCode.Count}");
Console.WriteLine($"FR: {string.Join(", ", namesByCode["FR"])}");
Keys: 2
FR: France, French Guiana
The lookup has 2 keys, FR and JP, and namesByCode["FR"] gave both names stored under FR.
Conclusion
ToDictionary turns a list into a dictionary: the key selector picks each item's key, and the value selector, if you give one, picks what's stored. Every key must be different and none can be null, and a comparer such as StringComparer.OrdinalIgnoreCase decides whether FR and fr count as the same key.
Additional Resources
Enumerable.ToDictionary— every form, with the exceptions each one throws.Dictionary<TKey,TValue>Class — how a dictionary stores keys and values, and the rules for keys.StringComparer.OrdinalIgnoreCase— the comparer that ignores case.Enumerable.ToLookup— one key with several values.
