Archiv für den Monat: Dezember 2013

C#: Lookup vs. Dictionary

Lookup (Namespace: System.Linq)

Lookup : ILookup : IEnumerable>

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:

var myList = new List>
                new KeyValuePair(30, "Sam"),
                new KeyValuePair(10, "Hans"),
                new KeyValuePair(10, "Fred"),
                new KeyValuePair(20, "Sepp"),
                new KeyValuePair(10, "Ron")

var myLookup = (Lookup) myList.ToLookup(

var len = myLookup.Count;
var entry = myLookup[10];

Dictionary (Namespace: System.Collections.Generic)

Dictionary : IDictionary 
: ICollection>, IEnumerable>, IEnumerable

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:

var myDictionary = new Dictionary();
myDictionary.Add(20, "Fred");

var len = myDictionary.Count;
var entry = myDictionary[10];

Blogpost Original Date: 16.02.2010, Updated: 13.12.2013