0
0
CsharpHow-ToBeginner · 2 min read

C# How to Convert List to Dictionary Easily

You can convert a list to a dictionary in C# using ToDictionary like this: var dict = list.ToDictionary(item => item.KeyProperty, item => item.ValueProperty); where you specify how to get keys and values from list items.
📋

Examples

Input["apple", "banana", "cherry"] with key = first letter, value = whole string
Output{"a": "apple", "b": "banana", "c": "cherry"}
Input[new Person {Id=1, Name="Alice"}, new Person {Id=2, Name="Bob"}] with key = Id, value = Name
Output{"1": "Alice", "2": "Bob"}
InputEmpty list
Output{}
🧠

How to Think About It

To convert a list to a dictionary, think about what you want to use as the key and what as the value for each item. Then, for each item in the list, pick the key and value and add them to the dictionary. This way, you map each unique key to its corresponding value.
📐

Algorithm

1
Get the input list.
2
Decide which property or value will be the dictionary key.
3
Decide which property or value will be the dictionary value.
4
For each item in the list, extract the key and value.
5
Add the key and value to the dictionary.
6
Return the dictionary.
💻

Code

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

class Program
{
    static void Main()
    {
        var fruits = new List<string> { "apple", "banana", "cherry" };
        var dict = fruits.ToDictionary(f => f[0], f => f);
        foreach (var kvp in dict)
            Console.WriteLine($"{kvp.Key}: {kvp.Value}");
    }
}
Output
a: apple b: banana c: cherry
🔍

Dry Run

Let's trace converting the list ["apple", "banana", "cherry"] to a dictionary using the first letter as key and the whole string as value.

1

Start with list

["apple", "banana", "cherry"]

2

Extract key and value for each item

Keys: 'a', 'b', 'c'; Values: "apple", "banana", "cherry"

3

Add to dictionary

{'a': "apple", 'b': "banana", 'c': "cherry"}

KeyValue
aapple
bbanana
ccherry
💡

Why This Works

Step 1: Use ToDictionary method

The ToDictionary method converts a list to a dictionary by specifying how to get keys and values from each item.

Step 2: Specify key selector

You provide a function like item => item.KeyProperty to tell which part of the item becomes the dictionary key.

Step 3: Specify value selector

You provide a function like item => item.ValueProperty to tell which part of the item becomes the dictionary value.

🔄

Alternative Approaches

Manual loop
csharp
var dict = new Dictionary<char, string>();
foreach (var f in fruits)
{
    dict[f[0]] = f;
}
More code but clearer for beginners; no LINQ needed.
Using ToLookup then ToDictionary
csharp
var lookup = fruits.ToLookup(f => f[0]);
var dict = lookup.ToDictionary(g => g.Key, g => g.First());
Useful if keys might repeat and you want first value per key.

Complexity: O(n) time, O(n) space

Time Complexity

The method loops through all list items once, so time grows linearly with list size.

Space Complexity

A new dictionary is created with one entry per list item, so space grows linearly.

Which Approach is Fastest?

Using ToDictionary is usually fastest and cleanest; manual loops are similar but more verbose.

ApproachTimeSpaceBest For
ToDictionaryO(n)O(n)Simple, readable, fast
Manual loopO(n)O(n)Beginners or no LINQ
ToLookup then ToDictionaryO(n)O(n)Handling duplicate keys gracefully
💡
Use ToDictionary with key and value selectors to convert lists quickly and clearly.
⚠️
Forgetting that dictionary keys must be unique, causing exceptions if duplicates exist in the list.