Have you ever felt a requirement of duplicate keys and value pairs in a dictionary? Sounds like crazy!!! But yes few days back I required to have a map/dictionary with multiple entries of same key with different values and then performing some operation like groupby and get the count blah.. blah...
So I couldn’t use the Dictionary object to fulfill my requirement as below is what you’ll get if you try to insert multiple keys inside a normal Dictionary object:
So googled around and finally endup reading a post of JonSkeet explaining how we can utilize LookUp for this problem. Well I got enlighten after reading the awesome post and decided to explore the Lookup class and its usage.
Well in the screenshot you can see that you can not insert duplicate entries in a Dictionary class so you do need a custom list to store those values. Here’s the sample code where I’ve crated a simple data class that is holding my key and value pairs.
Now you can use a List<Data> to store those items in this:
But this is not actual key value pair collection that we needed. So, you all familiar with the LINQ and its Extension methods on any IEnumerable. Just checkout the ToLookup function, this is what we’ll use to convert this list to an key value pair collection.
Now we have this groupedData collection which is of type IGroupInfo<string, int> in our case. so we can apply the grouping operations and find the multiple values related to a Key.
When you run this program you’ll get the output:
Beautiful !! isn’t it? We got all the keys and corresponding values in place.
you can ask, If it’s a dictionary then Would I be able to get the values corresponding to a key using indexer? Answer is: YES.
Go ahead and use indexer of keys and get all the values as IEnumerable. Check this out:
This was my first encounter with Lookup and I liked it. Hope you do feel the same.