Maps Keys to a Collection of Values using Lookup Collection

By | September 12, 2011

Most of us are very familiar with Dictionary Collection which supports only one value per key mapping. But, what if, if you came across with some situation where you need to map keys with collection of elements ? Do we really need to create a custom collection ? I will say, NO.  C# provides another Collection type called Lookup as a part of .NET Framework 3.5 which maps keys into a collection of values. This tip is all about using the Lookup Collection with a small demonstration.

As said, Lookup is a collection of keys each mapped to one or more values, so here is the representation of the collection Lookup<TKey, TElement> . Where TElement is the new collection type of elements.

Before going forwards, lets create a customer entity class which will represent the customer collection.

image

In next step create the  Customer Collection, as shown in below code snippet

image

Now, before defining a Lookup Collection, we need to know some basic fundamentals . Like Dictionary we can not create a Lookup Collection directly. While creating the instance of the  Lookup collection object, we need to invoke an extension method called ToLookup()  which will be returning a Lookup<Tkey, TElement> object. 

Following code snippet shows creation of a Lookup Collection with key type of Boolean with Customer Collection.image

customers.ToLookup(cust => cust.Status) will  pass  Lookup<bool, Customer>  to customerLookup Collection. The Lookup collection created on key type of Boolean. Hence we can access the elements as follows,

image

before looking into further details, lets have a quick look at resulting output.

image

We have the expected result.  Lookup<bool, Customer> customerLookup is the container of a Collection of Customer with  bool value and represent as below.

image

I hope, above picture talks everything about the representation of Customer collection as a Lookup which maps with Boolean keys.

For More information Read this article from MSDN

Hope this helps !

Cheers !

Abhijit