C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
String, value: The MultiMap here uses a string key and any type of value. We add objects at specific keys.
ClassGeneric Class, MethodAdd: It provides a simple Add method. This method is implemented with TryGetValue.
TryGetValueContainsKeyLogic: To continue, we have code add the value to the List. The value is always stored at its key, even with duplicates.
Keys: The MultiMap exposes Keys. You will want to enumerate over Keys in your code.
C# program that implements MultiMap
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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);
}
}
}
}
Output
MULTIMAP: key1=True
MULTIMAP: key1=False
MULTIMAP: key2=False
MULTIMAP2: animal=cat
MULTIMAP2: animal=dog
MULTIMAP2: human=tom
MULTIMAP2: human=tim
MULTIMAP2: mineral=calcium
Note: The original implementation of MultiMap here did not add a new list to the Dictionary upon creation in the indexer.
However: This reduced the usefulness of the indexer. Artem Korneev wrote in with the improved implementation of get.