Automatically creating a collection in the Dictionary<Key, Collection<Value>>

.net, c#, collections, dictionary

Solution

You could create something like Google Java Collection's Multimap... or you could just add an extension method like this:

public static void AddValue<TKey, TValue>
    (this IDictionary<TKey, List<TValue>> dictionary, TKey key, TValue value)
{
    List<TValue> values;
    if (!dictionary.TryGetValue(key, out values))
    {
        values = new List<TValue>();
        dictionary.Add(key, values);
    }
    values.Add(value);
}

As Bevan says, `Lookup` can help as well - but you can only create one with the `ToLookup` method, and you can't modify it afterwards. In many cases that's a thoroughly good thing, but if you need a mutable map then you'll ned something like the above.

Problem

Lot of times I have to create a `Dictionary<KeyType, List<ValueType>>` Before I can start using the dictionary I have to first verify that List has been created for that key. ``` //Can i remove these two lines? if(!dict.ContainsKey(key)) dict[key]= new List<ValueType>; //now use the key dict[key].Add(value); ``` I know its only "2 lines" of code but it annoys me and I think it can be removed. I can extend dictionary in someway but before I do it, I want to know if someone has found a clever way to remove the above `if` statement. Basically i want to create a `Dictionary<KeyType, Collection<ValueType>>` and start using it right away like `dict[key].Add(value)`.

Original source