Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Dictionary item on the fly with operator[]

Normally when you create a Dictionary<Tkey, TValue> you have to first go and add k/v pairs by calling add on the dictionary itself.

I have a Dictionary<string, mycontainer> where mycontainer is a container of other objects. I need to be able to add things to the mycontainer quickly so I thought maybe I can overload the subscript operator[] to create a mycontainer on the fly if it doesn't already exist and then allowing me to call add on it directly, as such:

mydictionnary["SomeName"].Add(myobject); without explicitly having to go create mycontainer every time a container with the said name doesn't exist in the dictionary.

I wondered if this is a good idea or should I explicitly create new mycontainer objects?

like image 503
Tony The Lion Avatar asked Jun 07 '11 11:06

Tony The Lion


2 Answers

You should make your own class that wraps a Dictionary<TKey, List<TItem>>.

The indexer would look like this:

public List<TItem> this[TKey key] {
    get {
        List<TItem> retVal;
        if (!dict.TryGetValue(key, out retVal))
            dict.Add(key, (retVal = new List<TItem>(itemComparer)));
        return retVal;
    }
}
like image 159
SLaks Avatar answered Nov 04 '22 20:11

SLaks


Might as well do myCustomClass.Add( key, subkey, value ); so the code can be easily understood and intellisense will guide it's usage.

like image 1
Robert Levy Avatar answered Nov 04 '22 18:11

Robert Levy