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.

  • http://weblogs.asp.net/psteele/archive/2010/02/12/lookups-vs-dictionaries.aspx Lookups vs. Dictionaries – Patrick Steele's .NET Blog

    [...] Felker has a great post that explains the different uses of LINQ's ToLookup and ToDictionary.  Check it out! Technorati Tags: .NET,LINQ Published Friday, February 12, 2010 10:15 AM by [...]

  • http://www.srtsolutions.com/blogs/patricksteele/archive/2010/02/12/lookups-vs-dictionaries.aspx Lookups vs. Dictionaries – Patrick Steele

    [...] Felker has a great post that explains the different uses of LINQ's ToLookup and ToDictionary.  Check it out! Technorati Tags: [...]

  • KingWhitey

    So a ToLookup is similar to a NameValueCollection?

  • http://www.justnbusiness.com/ Justin Chase

    So what's the difference between a lookup and a hashtable?

  • http://java.webdevinsider.com/multithreaded-programming-with-java-technology-in-java/ Multithreaded Programming with Java Technology in java | Java WebDev Insider

    [...] LINQ: ToLookup vs ToDictionary « this.Reflect() [...]

  • http://dotnetblog.saschabaumann.com/2010/02/c-loopup-vs-dictionary/ C#: Loopup vs. Dictionary | DotNetBlog der DotNet-Blog – von Sascha Baumann

    [...] A nice article about using ToDictionary and ToLookup in Linq can be found @blog.donnfelker.com Share and [...]

  • Ross

    @Justin Chase: A lookup has a little more plumbing to it. Lookup(of TKey, TValue) is essentially Hashtable(ofTKey, IEnumerable(Of TValue)).

  • http://www.justnbusiness.com/ Justin Chase

    I see, but multiple keys can point to the same value? Sort of a reverse hashtable?

  • http://www.easyrecovery.ie data recovery

    Does it supports Array with Oops?

  • http://www.saleboots.co.uk ugg boots

    Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
    Jordan Pro Classic
    If its common it might be difficult to get, however, be creative and you can usually find something.

  • http://bani.deocazie.info Bani Pe Net

    nice script you put up. very usefull

  • Xx

    Shouldn't a lookup be described as having multiple values for the same key rather than multiple keys of the same value?

  • http://twitter.com/ksnavinkumar NavinKumar.K.S

    Nice Article Donn i am NavinKumar from India. i like to know many things like this concept can you please help me

  • http://twitter.com/ksnavinkumar NavinKumar.K.S

    Hi Donn,
    i like this article its is very useful.

  • http://twitter.com/arviman Arvind B

    Yes, you’re correct. Since each key has a IEnumerable<tvalue> as it’s value.

  • http://twitter.com/arviman Arvind B

    There’s no reason why multiple keys ‘shouldn’t’ point to the same object.

  • Stevehalennss

    This article is very interesting and more useful and I like this article very much. The difference  linq tolookup vs todictionary is massive..
    ————
    Stevehalen
    DNS Lookup

  • http://paperswriting.com/ custom writing help

    I think the mapping is done by defining classes that correspond to the tables in the database, and containing all or a subset of the columns in the table as data members

  • Toaihv

    Great post. Many thanks !!!

  • haha

    replica designer bags I recommend the package
    replica designer handbags Of inexpensive package
    air max 2012 Comfortable shoes
    nike shox turbo Cheap shoes
    men puma shoes Unique design Shoes
    air max 90 Variety of shoe styles
    wholesale puma shoes Pretty shoes
    puma shoes sale Cheap comfortable shoes
    timberland mens boots  Discount a lot of
    gucci women shoes Quite well shoes
    louis vuitton outlet Very nice

  • Coach Factory Online

    Business coaching is an informal, open affair. You will meet with the coach and he will assess your business’s needs, and then tailor his services to your precise requirements.

  • Coach Factory Outlet
  • Coach Factory Outlet