C# MultiMap Class

Generic type

You want to implement a MultiMap class in the C# programming language. This allows you to add multiple values to a single key in a Dictionary. Here we see an example implementation of the MultiMap associative array in the C# language, and also several usages of this class.

This C# article implements a MultiMap generic class. MultiMap uses many values per key.

Implementation

Note

First, you will find that the base class library does not provide a MultiMap in the framework directly. MultiMap is a Dictionary with values of type List. Here we will show a MultiMap façade class. What it does is use a string key and any type of value. Then you can use its simple methods to add objects at specific keys. You can find more on generic classes on this website as well.

Class Examples
Program that implements MultiMap [C#]

using System;
using System.Collections.Generic;

public class MultiMap<V>
{
    // 1
    Dictionary<string, List<V>> _dictionary = new Dictionary<string, List<V>>();

    // 2
    public void Add(string key, V value)
    {
	List<V> list;
	if (this._dictionary.TryGetValue(key, out list))
	{
	    // 2A.
	    list.Add(value);
	}
	else
	{
	    // 2B.
	    list = new List<V>();
	    list.Add(value);
	    this._dictionary[key] = list;
	}
    }

    // 3
    public IEnumerable<string> Keys
    {
	get
	{
	    return this._dictionary.Keys;
	}
    }

    // 4
    public List<V> this[string key]
    {
	get
	{
	    List<V> list;
	    if (this._dictionary.TryGetValue(key, out list))
	    {
		return list;
	    }
	    else
	    {
		return new List<V>();
	    }
	}
    }
}
Steps

Overview. In step 1, it uses a Dictionary of string keys. This code always uses string keys, which are the most common. Its goal is to simplify. In step 2, it provides a simple Add method. This method is implemented with TryGetValue, and therefore usually has better performance than ContainsKey.

Further steps. In step 2A, it adds the value to the List. The value is always stored at its key, even with duplicates. In step 3, it exposes Keys. You will want to enumerate over Keys in your code. In step 4, it provides an indexer. This provides natural and short syntax for accessing the MultiMap. Note that it returns an empty list if nothing exists. You can find more details on indexers here.

Indexer Examples

Bool example

What follows is a very simple console program that uses the MultiMap shown above. It demonstrates the Add method, and loops through all the Keys and then the values. The two "key1" strings indicate the same value location, so the second value is added to the first in the List.

Program that uses MultiMap with bools [C#]

class Program
{
    static void Main()
    {
	bool b1 = true;
	bool b2 = false;
	bool b3 = false;

	MultiMap<bool> m1 = new MultiMap<bool>();
	m1.Add("key1", b1);
	m1.Add("key1", b2);
	m1.Add("key2", b3);

	foreach (string k in m1.Keys)
	{
	    foreach (bool b in m1[k])
	    {
		Console.WriteLine(k + "=" + b);
	    }
	}
	Console.ReadLine();
    }
}

Output

key1=True
key1=False
key2=False

String example

This example shows how you could use MultiMap with strings to store names within categories. The strings "cat" and "dog" will both be stored under "animal".

Program that uses MultiMap with strings [C#]

class Program
{
    static void Main()
    {
	const string s1 = "cat";
	const string s2 = "dog";

	MultiMap<string> m1 = new MultiMap<string>();
	m1.Add("animal", s1);
	m1.Add("animal", s2);
	m1.Add("human", "tom");
	m1.Add("human", "tim");
	m1.Add("mineral", "calcium");

	foreach (string k in m1.Keys)
	{
	    foreach (string v in m1[k])
	    {
		Console.WriteLine(k + "=" + v);
	    }
	}

	Console.ReadLine();
    }
}

Output

animal=cat
animal=dog
human=tom
human=tim
mineral=calcium

Summary

The C# programming language

Here we saw an implementation of the MultiMap class in the C# language. My advice is to keep it simple. If you don't need a complex class, it is best to use the minimum that meets your needs. The façade here simplifies Dictionary and wraps it with MultiMap features.

Collections
.NET