Lesson 20/31

Tutorials LINQ Mastery

ToDictionary vs ToLookup: One-to-One vs One-to-Many

On this page

Index-Accelerated Data

Pulling data from a list is O(N). Pulling from a Dictionary or Lookup is O(1). Choosing the right mapping structure is critical for performance.

1. ToDictionary (Unique Keys)

Creates a 1:1 mapping. Every key MUST be unique. If ToDictionary encounters a duplicate key, it throws an ArgumentException. **Use Case:** Mapping User objects by their unique ID.

2. ToLookup (One-to-Many)

Creates a 1:Many mapping. It's essentially a Dictionary<TKey, IEnumerable<TElement>>. If multiple items share the same key, it groups them together into a collection. **Use Case:** Grouping Employees by their Department ID.

3. Lookup Resilience

Unlike a Dictionary, a Lookup is immutable and **Null-Safe**. If you try to access a key that doesn't exist in a Lookup, it returns an empty sequence instead of throwing a 'KeyNotFoundException'. This makes your code much cleaner and less 'branchy'.

3. Architect Insight

Q: "Should I call ToDictionary inside a loop?"

Architect Answer: "NO! This is a common performance killer. Create the Dictionary/Lookup **once** before the loop starts, and then do O(1) lookups inside. A 'ToDictionary' involves copying all data and calculating hashes—it's expensive."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

LINQ Mastery
Course syllabus
General
1. Core Foundations
2. Filtering & Transformation
3. Aggregation & Quantifiers
4. Ordering & Partitioning
5. Sets & Lookups
6. Join & Grouping
7. Advanced Providers & Parallelism
8. Real-world Performance & Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details