Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

LINQ: ToLookup vs ToDictionary

Some people are not sure of the difference between ToLookup vs ToDictionary LINQ methods.

To break it down real simple:

  • One is a look up (ToLookup)
  • One is a dictionary (ToDictionary)

Duh. That’s what you’re probably thinking. The real difference is understanding what each of these data structures do.

Lookups

A lookup is a key value pair in which multiple keys of the same value can exist, therefore resulting in a “lookup” type of scenario. The perfect example for this is to assume that we have a List of Author objects. The author object contains the following:

  • First Name
  • Last Name
  • Year their first book was published
  • Social Security Number

Assume that we’d like to give the user the option to select the authors based upon the year they published their first book in a WPF app. We could do that like this:

// Returns a list of Authors
var authors = authorService.FindAll();

// Turn the list into a lookup for later use
var authorLookup = authors.ToLookup(k => k.YearFirstPublished, v => v);

// Further down in the code
// Find all authors who published their first book in 1969
// Returns an enumerable of Authors that match that lookup value
var authorsPublishedInParticularYear = authorLookup[1969];

This will return all authors who published their first book in 1969. We could use this look up later in the application as well to look up other values.

The key thing to note here is that a Lookup can have multiple keys of the same value.

Dictionaries

A dictionary is a key value pair in which a key can only exist once within the dictionary. You cannot have two entries with the same key. This is the difference between the Dictionary and Lookup data structures.

Using the same Author object we described above we can find an author by their Social Security Number if we turned the list into a dictionary for fast lookups based upon a unique key (the social security number).

This will return a single Author object who’s social security number matches ‘555-55-5555’.

// Returns a list of Authors
var authors = authorService.FindAll();

// Turn the list into a lookup for later use
var authorDictionary = authors.ToDictionay(k => k.SocialSecurityNumber, v => v);

// Further down in the code
// Finds the author with 555-55-5555 as their Social Security Number
var author = authorDictionary["555-55-5555"];

Conclusion

While dictionaries and lookups seem to be nearly the same data structure, they provide completely different functionality based upon the value the key possesses.