Maps Keys to a Collection of Values using Lookup Collection

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.


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


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,


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


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


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 Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.