ToDictionary method in C#

The ToDictionary method is a LINQ extension method in C# that converts any collection into a Dictionary<TKey, TValue>. It allows you to specify how to extract the key and value from each element in the source collection.

Syntax

Following is the basic syntax for the ToDictionary method −

source.ToDictionary(keySelector)
source.ToDictionary(keySelector, valueSelector)
source.ToDictionary(keySelector, valueSelector, comparer)

Parameters

  • keySelector − A function to extract the key from each element.

  • valueSelector − A function to extract the value from each element (optional).

  • comparer − An equality comparer to compare keys (optional).

Return Value

Returns a Dictionary<TKey, TValue> containing the keys and values selected from the source collection.

Using ToDictionary with Key and Value Selectors

You can convert a collection to a dictionary by specifying both key and value extraction logic −

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

class Demo {
    static void Main() {
        string[] vehicles = new string[] {"Car", "Bus", "Bicycle"};
        
        // Convert to dictionary with string as key and boolean as value
        var dictionary = vehicles.ToDictionary(item => item, item => true);
        
        foreach (var element in dictionary) {
            Console.WriteLine("{0}, {1}", element.Key, element.Value);
        }
    }
}

The output of the above code is −

Car, True
Bus, True
Bicycle, True

Using ToDictionary with Index as Key

You can use the element's index as the key and the element itself as the value −

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

class Demo {
    static void Main() {
        string[] fruits = {"Apple", "Banana", "Cherry"};
        
        // Use index as key and fruit name as value
        var fruitDictionary = fruits.Select((fruit, index) => new { fruit, index })
                                   .ToDictionary(x => x.index, x => x.fruit);
        
        foreach (var item in fruitDictionary) {
            Console.WriteLine("Index: {0}, Fruit: {1}", item.Key, item.Value);
        }
    }
}

The output of the above code is −

Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Cherry

Using ToDictionary with Custom Objects

You can convert a collection of custom objects to a dictionary using object properties −

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

class Student {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

class Demo {
    static void Main() {
        List<Student> students = new List<Student> {
            new Student { Id = 1, Name = "Alice", Age = 20 },
            new Student { Id = 2, Name = "Bob", Age = 22 },
            new Student { Id = 3, Name = "Charlie", Age = 21 }
        };
        
        // Use Id as key and Name as value
        var studentDictionary = students.ToDictionary(s => s.Id, s => s.Name);
        
        foreach (var student in studentDictionary) {
            Console.WriteLine("ID: {0}, Name: {1}", student.Key, student.Value);
        }
    }
}

The output of the above code is −

ID: 1, Name: Alice
ID: 2, Name: Bob
ID: 3, Name: Charlie

Key Rules

  • All keys must be unique − duplicate keys will throw an ArgumentException.

  • If no value selector is provided, the entire element becomes the value.

  • The method requires using System.Linq; namespace.

  • Keys cannot be null unless a custom comparer allows it.

Conclusion

The ToDictionary method provides a convenient way to convert any collection into a Dictionary by specifying key and value extraction logic. It's particularly useful when you need fast key-based lookups from existing collections or when transforming data structures in LINQ queries.

Updated on: 2026-03-17T07:04:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements