MultiMap
A MultiMap
has multiple values at a key. With it we add multiple values to a single key in a Dictionary
. In C#, MultiMaps
can be useful.
We see an example implementation of the MultiMap
associative array in the C# language. We then use the class
. This is not an ideal implementation—but it works.
The base class library does not provide a MultiMap
. This type is a Dictionary
with values of type List
. Here we show a MultiMap
facade class
.
MultiMap
here uses a string
key and any type of value. We add objects at specific keys.MultiMap
provides a simple Add method. This method is implemented with TryGetValue
.List
. The value is always stored at its key, even with duplicates.MultiMap
exposes Keys
. You will want to enumerate over Keys
in your code.using System; using System.Collections.Generic; public class MultiMap<V> { Dictionary<string, List<V>> _dictionary = new Dictionary<string, List<V>>(); public void Add(string key, V value) { // Add a key. List<V> list; if (this._dictionary.TryGetValue(key, out list)) { list.Add(value); } else { list = new List<V>(); list.Add(value); this._dictionary[key] = list; } } public IEnumerable<string> Keys { get { // Get all keys. return this._dictionary.Keys; } } public List<V> this[string key] { get { // Get list at a key. List<V> list; if (!this._dictionary.TryGetValue(key, out list)) { list = new List<V>(); this._dictionary[key] = list; } return list; } } } class Program { static void Main() { // Create first MultiMap. var multiMap = new MultiMap<bool>(); multiMap.Add("key1", true); multiMap.Add("key1", false); multiMap.Add("key2", false); foreach (string key in multiMap.Keys) { foreach (bool value in multiMap[key]) { Console.WriteLine("MULTIMAP: " + key + "=" + value); } } // Create second MultiMap. var multiMap2 = new MultiMap<string>(); multiMap2.Add("animal", "cat"); multiMap2.Add("animal", "dog"); multiMap2.Add("human", "tom"); multiMap2.Add("human", "tim"); multiMap2.Add("mineral", "calcium"); foreach (string key in multiMap2.Keys) { foreach (string value in multiMap2[key]) { Console.WriteLine("MULTIMAP2: " + key + "=" + value); } } } }MULTIMAP: key1=True MULTIMAP: key1=False MULTIMAP: key2=False MULTIMAP2: animal=cat MULTIMAP2: animal=dog MULTIMAP2: human=tom MULTIMAP2: human=tim MULTIMAP2: mineral=calcium
The MultiMap
provides an indexer. This provides natural and short
syntax for accessing the MultiMap
. It returns an empty List
if nothing exists.
The Main()
method shows how to use the MultiMap
to store bool
and string
values. It is fairly simple to figure out, and can be extended in many ways.
We saw an implementation of the MultiMap
class
in the C# language. The facade pattern here simplifies Dictionary
and wraps it with MultiMap
features.