C#: Lookup vs. Dictionary


Published: 13.12.2013

Lookup (Namespace: System.Linq)

A Lookup is a collection which implements the ILookup Interface. It was introduces with LINQ and can be used instead of Dictionary.

A key don’t has to be unique, so you can have multiple entries with the same key. Also the Lookup is immutable, that means you can not add values on the fly, like you could with a List or Dictionary. You can however determine its count (.Count) and you can access the items with [value].

When you look up a key that does not exist in the Lookup, you don’t get a KeyNotFound-Exception but an empty sequence instead.

You cannot directly instantiate a Lookup, it is a result of a LINQ-Selection, which needs a Func for Key-Selection and a Func for Value selection.

Here is an example:

Dictionary (Namespace: System.Collections.Generic)

A key has to be unique, so you can have only one multiple entry with the same key. The Dictionary is mutable, that means you can add values on the fly. Also you can use normal collection methods to determine its count (.Count) and to access the items with [value].

When you look up a key that does not exist you get a KeyNotFound-Exception.
You can directly instantiate a Dictionary.

Here is an example:

Blogpost Original Date: 16.02.2010, Updated: 13.12.2013

8 Gedanken zu „C#: Lookup vs. Dictionary

  1. Rainer Hilmer

    Does anybody know the .net framework completely? Well, I have to admit I don’t. It’s the first time I read about Lookup(of T). So thank you for the hint. 🙂

  2. Marco Scheel

    Hi,

    greetings from offenbach. Never heard of loopups… maybe you should correct it to lookups 😉 … but as rainer said…. never heard of lookups too. great info.

    Ciao Marco

    1. Sascha Baumann

      Thanks Marco, how did this happen ? damn ;o)

      I never heard of them, too – always used Collection of KeyValue Pairs for this kind of stuff.

      Greetings from Berlin to Offenbach
      Sascha

    1. Sascha Baumann

      Hi Niva, Interesting Website. Comparing Performance of Lookup and Dictionary might be something for the next update, if I can manage to find some information about it – or measure myself.
      Cheers
      Sascha

    1. Sascha Baumann

      Hi there,

      for a LookUp, a Key does NOT have to be unique. This is a main difference to a Dictionary, where a key has alway to be unique.
      Hope I cleared that up.
      Ciao
      Sascha

Kommentare sind geschlossen.