Is there a C# data structure to map keys to multiple values? I have a collection of items that I want to key by name; however, the name is not unique. Hashtable and Dictionary only allow unique keys. Lookup seems close to what I want; however, it is not mutable.
Is there a built in data structure that I’m missing or do I need to build one myself?
What you’re looking for is a multimap.
You may want to take a look at the answer to this question.
You may also want to look into the C5 Generic Collection library, which is free and has an implementation of a multimap.
If you feel like rolling your own, a simple place to start is a dictionary of lists:
However, you can’t add to such a dictionary the normal way. You have to first check if the key already exists, and if so, fetch the value (list) and add to it. Otherwise, you need to create the list and populate it with a value.
If you are so inclined, I would suggest you consider using a set of extension methods to simplify the Add/Remove operations: