ToDictionary and ToLookup in C#: Convert a List to a Dictionary

Pass a key selector and C# LINQ ToDictionary turns a list into a Dictionary<TKey, TValue> in one call. Here the customer ID becomes the key:

var byId = Customers.ToDictionary(c => c.Id);
Console.WriteLine(byId[102].Name);   // Tyler Brooks

The catch is that two items can’t share a key. I ran the duplicate-key crash, three fixes and ToLookup for one-to-many data on .NET 10 with five US customers.

C# LINQ ToDictionary Syntax and Overloads

ToDictionary lives in System.Linq and runs right away, unlike most LINQ operators. These are the calls you’ll actually use:

CallBuildsSince
list.ToDictionary(x => x.Id)Key -> the whole itemAny .NET
list.ToDictionary(x => x.Id, x => x.Name)Key -> a value you pickAny .NET
ToDictionary(keySelector, comparer)Custom key equality (ignore case)Any .NET
pairs.ToDictionary()From KeyValuePair or (key, value) tuples.NET 8+
list.ToLookup(x => x.State)Key -> many itemsAny .NET

Every demo includes this Data.cs and runs as a .NET 10 file-based app with dotnet run:

using System.Globalization;

public record Customer(int Id, string Name, string City, string State, string Zip);
public record Order(int OrderId, int CustomerId, decimal Total);

public static class Shop
{
    public static List<Customer> Customers =
    [
        new(101, "Jenna Morales", "Austin", "TX", "78701"),
        new(102, "Tyler Brooks", "Denver", "CO", "80202"),
        new(103, "Dana Whitfield", "Albany", "NY", "12207"),
        new(104, "Marcus Lee", "Dallas", "TX", "75201"),
        new(105, "Rachel Kim", "Boulder", "CO", "80302"),
    ];

    public static List<Order> Orders =
    [
        new(5001, 101, 129.99m), new(5002, 102, 48.50m),
        new(5003, 101, 310.00m), new(5004, 104, 75.25m),
    ];

    public static string Usd(decimal d) => d.ToString("C", CultureInfo.GetCultureInfo("en-US"));
}

Notice that TX and CO each appear twice. That’s on purpose.

Convert a List to a Dictionary with a Key and Element Selector

With one lambda, the value is the whole record. Add a second lambda (the element selector) to store just the part you need:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

Dictionary<int, Customer> byId = Customers.ToDictionary(c => c.Id);
Console.WriteLine($"{byId.Count} customers, #102 is {byId[102].Name}");

Dictionary<int, string> cityById =
    Customers.ToDictionary(c => c.Id, c => $"{c.City}, {c.State}");
foreach (var (id, city) in cityById)
    Console.WriteLine($"{id}: {city}");

var totals = Orders.ToDictionary(o => o.OrderId, o => o.Total);
Console.WriteLine($"Order 5003 total: {Usd(totals[5003])}");

Output:

5 customers, #102 is Tyler Brooks
101: Austin, TX
102: Denver, CO
103: Albany, NY
104: Dallas, TX
105: Boulder, CO
Order 5003 total: $310.00
C# LINQ ToDictionary in VS Code: a customer list keyed by Id, an element selector mapping Id to city and state, and order totals in USD
ToDictionary with a key selector, then with an element selector

You get 5 customers keyed by ID, a city map, and order 5003’s total of $310.00. Records make good values here; my record vs class guide explains why.

Why Does ToDictionary Throw “An Item with the Same Key Has Already Been Added”?

Because a dictionary key must be unique, and ToDictionary doesn’t skip repeats. Key the same list by state and it fails on the second TX customer:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

try
{
    var byState = Customers.ToDictionary(c => c.State);
}
catch (ArgumentException ex)
{
    Console.WriteLine(ex.GetType().Name);
    Console.WriteLine(ex.Message);
}

Output:

ArgumentException
An item with the same key has already been added. Key: TX
C# ToDictionary duplicate key error: ArgumentException An item with the same key has already been added. Key: TX in the VS Code terminal
The second TX customer stops the whole conversion

On .NET 10 the message ends with the key (TX), which makes the bad row easy to find. I’d catch it in a try-catch block only for logging; the real fix is picking a strategy for duplicates.

3 Ways to Fix Duplicate Keys in ToDictionary

Same list, same state key, three different answers to “what do I do with the second TX row?”:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

// Fix 1: GroupBy + First keeps the first customer per state
var first = Customers.GroupBy(c => c.State)
    .ToDictionary(g => g.Key, g => g.First().Name);
Console.WriteLine("GroupBy + First: " + string.Join(", ", first));

// Fix 2: DistinctBy drops repeated keys, then ToDictionary
var distinct = Customers.DistinctBy(c => c.State)
    .ToDictionary(c => c.State, c => c.Name);
Console.WriteLine("DistinctBy:      " + string.Join(", ", distinct));

// Fix 3: ToLookup keeps every customer per state
var all = Customers.ToLookup(c => c.State, c => c.Name);
foreach (var g in all)
    Console.WriteLine($"ToLookup {g.Key}: {string.Join(", ", g)}");

Output:

GroupBy + First: [TX, Jenna Morales], [CO, Tyler Brooks], [NY, Dana Whitfield]
DistinctBy:      [TX, Jenna Morales], [CO, Tyler Brooks], [NY, Dana Whitfield]
ToLookup TX: Jenna Morales, Marcus Lee
ToLookup CO: Tyler Brooks, Rachel Kim
ToLookup NY: Dana Whitfield
C# fix duplicate keys in ToDictionary with GroupBy and First, DistinctBy then ToDictionary, and ToLookup keeping both TX and CO customers
GroupBy + First and DistinctBy keep one row per state; ToLookup keeps all of them
  • GroupBy + First: one row per key, and you choose which one (First, Last, MaxBy).
  • DistinctBy: the shortest way to keep the first row per key (.NET 6+). It’s covered in depth in Distinct and DistinctBy in C#.
  • ToLookup: keep every row. TX holds Jenna Morales and Marcus Lee.

Both one-row fixes return Jenna for TX and Tyler for CO, because they keep the first match in list order.

ToDictionary with StringComparer.OrdinalIgnoreCase

String keys are case-sensitive by default. Pass a comparer as the second argument when “denver” and “Denver” should be the same key:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

var byCity = Customers.ToDictionary(c => c.City, StringComparer.OrdinalIgnoreCase);
Console.WriteLine($"denver -> ZIP {byCity["denver"].Zip}");
Console.WriteLine($"BOULDER found: {byCity.ContainsKey("BOULDER")}");

var strict = Customers.ToDictionary(c => c.City);
Console.WriteLine($"Default comparer, denver found: {strict.ContainsKey("denver")}");

Output:

denver -> ZIP 80202
BOULDER found: True
Default comparer, denver found: False

The ignore-case map finds “denver” (ZIP 80202) and “BOULDER”, while the default one says False for “denver”. Keep in mind that the comparer also turns “Austin” and “austin” into a duplicate key.

The same comparer trick works anywhere you match text, as in comparing a string with multiple values.

ToDictionary on a List of KeyValuePair or Tuples (.NET 8+)

If your data is already pairs, .NET 8 added a parameterless ToDictionary(). It works on KeyValuePair lists and on (key, value) value tuples:

#:property PublishAot=false

List<KeyValuePair<string, string>> pairs =
[
    new("TX", "Austin"), new("CO", "Denver"), new("NY", "Albany"),
];
Dictionary<string, string> capitals = pairs.ToDictionary();
Console.WriteLine($"KeyValuePair list: {capitals.Count} keys, TX = {capitals["TX"]}");

(string Zip, string City)[] zips = [("78701", "Austin"), ("80202", "Denver")];
Dictionary<string, string> cityByZip = zips.ToDictionary();
Console.WriteLine($"Tuple array: 80202 = {cityByZip["80202"]}");

var noNewYork = capitals.Where(kv => kv.Key != "NY").ToDictionary();
Console.WriteLine($"Filtered copy: {string.Join(", ", noNewYork.Keys)}");

Output:

KeyValuePair list: 3 keys, TX = Austin
Tuple array: 80202 = Denver
Filtered copy: TX, CO

No lambdas needed. The last line is the handy one: filter a dictionary with Where and turn the result straight back into a dictionary. On .NET 7 or older, write ToDictionary(kv => kv.Key, kv => kv.Value) instead.

ToLookup in C#: One Key, Many Values

ToLookup returns an ILookup<TKey, TElement>: a read-only, one-to-many dictionary. Same five customers, grouped by state:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

ILookup<string, Customer> byState = Customers.ToLookup(c => c.State);

Console.WriteLine($"States: {byState.Count}");
Console.WriteLine($"TX customers: {byState["TX"].Count()}");
foreach (var c in byState["CO"])
    Console.WriteLine($"  CO: {c.Name} ({c.Zip})");

IEnumerable<Customer> florida = byState["FL"];   // no FL customers
Console.WriteLine($"FL customers: {florida.Count()}");
Console.WriteLine($"Contains(\"FL\"): {byState.Contains("FL")}");

Output:

States: 3
TX customers: 2
  CO: Tyler Brooks (80202)
  CO: Rachel Kim (80302)
FL customers: 0
Contains("FL"): False
C# ToLookup by state in VS Code: 3 states, 2 TX customers, the CO customers with ZIP codes, and a missing FL key returning 0 items
A missing key in an ILookup returns an empty sequence, not an exception

You get 3 states and 2 TX customers. The best part is byState["FL"]: there’s no FL customer, so it returns an empty sequence instead of throwing. Use Contains when you need to know whether the key exists.

ToLookup vs GroupBy: Immediate vs Deferred Execution

They look alike, but ToLookup builds its groups once, right away. GroupBy is deferred and regroups every time you enumerate it. A counter in the key selector proves it:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

int calls = 0;
var lookup = Customers.ToLookup(c => { calls++; return c.State; });
Console.WriteLine($"After ToLookup: {calls} key calls");

calls = 0;
var groups = Customers.GroupBy(c => { calls++; return c.State; });
Console.WriteLine($"After GroupBy:  {calls} key calls");
_ = groups.Count();
_ = groups.Count();
Console.WriteLine($"After 2 loops:  {calls} key calls");

Customers.Add(new(106, "Olivia Grant", "Miami", "FL", "33101"));
Console.WriteLine($"Lookup FL: {lookup["FL"].Count()}");
Console.WriteLine($"GroupBy FL: {groups.Count(g => g.Key == "FL")}");

Output:

After ToLookup: 5 key calls
After GroupBy:  0 key calls
After 2 loops:  10 key calls
Lookup FL: 0
GroupBy FL: 1
C# ToLookup vs GroupBy proof: ToLookup calls the key selector 5 times immediately, GroupBy 0 times until enumerated and 10 times after two loops
ToLookup runs once up front; GroupBy re-runs on every loop and sees the new FL customer

ToLookup made 5 key calls up front. GroupBy made 0 until I looped, then 10 after two loops. After I added a Miami customer, the lookup still said 0 for FL and GroupBy said 1.

Pro Tip: if you’ll read the groups more than once, call ToLookup (or ToList) once and reuse it. My LINQ GroupBy guide shows more group shapes.

ToLookup vs Dictionary<TKey, List<T>>

A dictionary of lists does the same grouping, but you can change it later. Here’s the trade-off on the same data:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

Dictionary<string, List<Customer>> byState = Customers
    .GroupBy(c => c.State)
    .ToDictionary(g => g.Key, g => g.ToList());

byState["TX"].Add(new(106, "Olivia Grant", "Houston", "TX", "77002"));
Console.WriteLine($"Dictionary TX after Add: {byState["TX"].Count}");

try { _ = byState["FL"]; }
catch (KeyNotFoundException) { Console.WriteLine("Dictionary FL: KeyNotFoundException"); }

ILookup<string, Customer> lookup = Customers.ToLookup(c => c.State);
Console.WriteLine($"Lookup FL: {lookup["FL"].Count()} items, no exception");

Output:

Dictionary TX after Add: 3
Dictionary FL: KeyNotFoundException
Lookup FL: 0 items, no exception
ILookup<K, T>Dictionary<K, List<T>>
Add items laterNo (read-only)Yes, dict[key].Add(...)
Missing keyEmpty sequenceKeyNotFoundException
Built withToLookupGroupBy + ToDictionary

I reach for ToLookup when I group once and only read. When orders keep arriving, the dictionary of lists wins. The C# Dictionary guide covers TryGetValue for the missing-key case.

ToFrozenDictionary for Read-Only Lookups (.NET 8+)

For a map you build once at startup and read millions of times, System.Collections.Frozen has ToFrozenDictionary. It’s slower to create but tuned for fast reads:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

using System.Collections.Frozen;

FrozenDictionary<string, Customer> byZip = Customers.ToFrozenDictionary(c => c.Zip);
Console.WriteLine($"80302: {byZip["80302"].Name}, {byZip["80302"].City}");
Console.WriteLine($"33101 found: {byZip.ContainsKey("33101")}");

List<KeyValuePair<string, string>> pairs = [new("TX", "Austin"), new("TX", "Dallas")];
Console.WriteLine($"Pairs with a repeated key: TX = {pairs.ToFrozenDictionary()["TX"]}");

try { Customers.ToFrozenDictionary(c => c.State); Console.WriteLine("Key selector: no exception"); }
catch (ArgumentException ex) { Console.WriteLine($"Key selector: {ex.Message}"); }

Output:

80302: Rachel Kim, Boulder
33101 found: False
Pairs with a repeated key: TX = Dallas
Key selector: An item with the same key has already been added. Key: TX

Lookups work like any dictionary: 80302 is Rachel Kim in Boulder, and 33101 isn’t there. The surprise is duplicates: the pair overload kept the last TX value (Dallas), and the key-selector overload threw the usual duplicate-key error.

Convert a List to a Dictionary Without LINQ (foreach + TryAdd)

Sometimes a plain loop is clearer, especially when you want to log each duplicate. TryAdd returns false instead of throwing, and the indexer overwrites. The basics of the source collection are in my List in C# guide:

#!/usr/bin/env dotnet
#:property PublishAot=false
#:include Data.cs
using static Shop;

var byState = new Dictionary<string, Customer>();
foreach (var c in Customers)
{
    if (!byState.TryAdd(c.State, c))
        Console.WriteLine($"Skipped {c.Name}: {c.State} is already taken");
}
Console.WriteLine($"{byState.Count} states: {string.Join(", ", byState.Keys)}");

var lastWins = new Dictionary<string, string>();
foreach (var c in Customers)
    lastWins[c.State] = c.Name;          // the indexer overwrites
Console.WriteLine($"Indexer keeps the last: TX = {lastWins["TX"]}");

Output:

Skipped Marcus Lee: TX is already taken
Skipped Rachel Kim: CO is already taken
3 states: TX, CO, NY
Indexer keeps the last: TX = Marcus Lee

TryAdd skips Marcus Lee and Rachel Kim and keeps 3 states (first wins). The indexer version keeps the last one, so TX ends up as Marcus Lee.

For more on working with collections, these pair well with this one:

Frequently Asked Questions

What is the difference between ToDictionary and ToLookup in C#?

ToDictionary maps each key to exactly one value and throws on a duplicate key. ToLookup maps each key to a sequence of values, accepts repeated keys, and returns an empty sequence for a key that isn’t there.

How do I convert a list to a dictionary when keys might repeat?

Decide which row wins: GroupBy(x => x.Key).ToDictionary(g => g.Key, g => g.First()) keeps the first, DistinctBy(x => x.Key) does the same in one step, and ToLookup keeps them all.

Does ToDictionary keep the order of my list?

Don’t rely on it. Dictionary<TKey, TValue> doesn’t promise an enumeration order. Freshly built dictionaries usually return items in insertion order, but sort the keys when the order matters.

Can a key from ToDictionary be null?

No. If the key selector returns null, ToDictionary throws ArgumentNullException. The Enumerable.ToDictionary reference on Microsoft Learn lists every overload and exception.

Is the ILookup returned by ToLookup editable?

No. ILookup has no Add or Remove. Rebuild it, or use a Dictionary<TKey, List<T>>. See the Enumerable.ToLookup docs for its overloads.