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.
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.
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.
Hope this helps !