0
0
CsharpHow-ToBeginner · 3 min read

How to Use LINQ ToDictionary in C# - Simple Guide

Use ToDictionary in LINQ to convert a collection into a dictionary by specifying a key selector and optionally a value selector. It creates a Dictionary<TKey, TValue> where each key is unique and maps to a value from the collection.
📐

Syntax

The ToDictionary method has two common forms:

  • collection.ToDictionary(keySelector): Creates a dictionary where keys come from keySelector and values are the original items.
  • collection.ToDictionary(keySelector, valueSelector): Creates a dictionary where keys come from keySelector and values come from valueSelector.

Both keySelector and valueSelector are functions that tell LINQ how to pick keys and values from each item.

csharp
var dictionary = collection.ToDictionary(item => item.KeyProperty, item => item.ValueProperty);
💻

Example

This example shows how to convert a list of people into a dictionary where the key is the person's ID and the value is their name.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        var people = new List<Person>
        {
            new Person { Id = 1, Name = "Alice" },
            new Person { Id = 2, Name = "Bob" },
            new Person { Id = 3, Name = "Charlie" }
        };

        var dictionary = people.ToDictionary(p => p.Id, p => p.Name);

        foreach (var kvp in dictionary)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}
Output
Key: 1, Value: Alice Key: 2, Value: Bob Key: 3, Value: Charlie
⚠️

Common Pitfalls

Common mistakes when using ToDictionary include:

  • Using a keySelector that produces duplicate keys, which causes an exception.
  • Not handling null values in keys or values if the dictionary does not allow them.
  • Confusing the order of keySelector and valueSelector parameters.

Always ensure keys are unique and handle possible duplicates before calling ToDictionary.

csharp
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var numbers = new List<int> { 1, 2, 2, 3 };

        // This will throw an exception because key 2 appears twice
        // var dict = numbers.ToDictionary(n => n);

        // Correct way: use Distinct() to remove duplicates first
        var dict = numbers.Distinct().ToDictionary(n => n);

        foreach (var kvp in dict)
        {
            Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
        }
    }
}
Output
Key: 1, Value: 1 Key: 2, Value: 2 Key: 3, Value: 3
📊

Quick Reference

Remember these tips when using ToDictionary:

  • Keys must be unique; duplicates cause exceptions.
  • You can select keys and values separately.
  • Use Distinct() or other methods to avoid duplicate keys.
  • The result is a Dictionary<TKey, TValue> for fast lookups.

Key Takeaways

Use ToDictionary to convert collections into dictionaries by specifying key and value selectors.
Ensure keys are unique to avoid runtime exceptions.
You can create dictionaries with keys and values from different properties.
Handle duplicates before calling ToDictionary using methods like Distinct().
The resulting dictionary allows fast access by keys.