Schlagwort-Archive: Lookup

C#: Lookup vs. Dictionary

Lookup (Namespace: System.Linq)

Lookup<Tkey, Tvalue> 
: ILookup<Tkey, Tvalue> 
: IEnumerable<IGroupin<<Tkey, Tvalue>>

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<KeyValuePair<int, string>>
            {
                new KeyValuePair<int, string>(30, "Sam"),
                new KeyValuePair<int, string>(10, "Hans"),
                new KeyValuePair<int, string>(10, "Fred"),
                new KeyValuePair<int, string>(20, "Sepp"),
                new KeyValuePair<int, string>(10, "Ron")
            };

var myLookup = (Lookup<int,string>) myList.ToLookup(
                                             (item)=>item.Key, 
                                             (item)=>item.Value
                                             );

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

Dictionary (Namespace: System.Collections.Generic)

Dictionary<Tkey, Tvalue> 
: IDictionary<Tkey, Tvalue>
: ICollection<KeyValuePair<Tkey, Tvalue>>, 
: IEnumerable<KeyValuePair<Tkey, Tvalue>>

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<int, string>();
myDictionary.Add(10,"Hans");
myDictionary.Add(20, "Fred");

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

Blogpost Original Date: 16.02.2010, Updated: 13.12.2013