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 开发者_StackOverflow中文版this is a good idea or should I explicitly create new mycontainer objects?
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;
}
}
Might as well do myCustomClass.Add( key, subkey, value );
so the code can be easily understood and intellisense will guide it's usage.
I would go for explicit code - implicit overloading of an indexer is not really a common situation and will probably bite in a few months time when someone else will be reading your code.
精彩评论