Create a dictionary on the fly using the [] operator

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

I have a Dictionary<string, mycontainer> , where mycontainer is a container of other objects. I need to be able to quickly add things to mycontainer, so I thought that maybe I could overload the operator[] index to create mycontainer on the fly if it does not already exist, and then allows me to directly call it an add as such:

mydictionnary["SomeName"].Add(myobject); without explicitly switching to creating mycontainer every time a container with the specified name does not exist in the dictionary.

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

+6
source share
3 answers

You must create your own class that wraps Dictionary<TKey, List<TItem>> .

The indexer will 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; } } 
+5
source

It is also possible to do myCustomClass.Add( key, subkey, value ); so that the code can be easily understood, and intellisense will determine its use.

+1
source

I would go for explicit code - the implicit overload of the indexer is not really a normal situation and will probably bite in a few months when someone else reads your code.

0
source

Source: https://habr.com/ru/post/889953/


All Articles