Monday, 28 January 2013

Use the Dictionary Indexer for upserts

If you have a Dictionary<T,T> and you want to upsert a value (i.e. update or insert depending on its existence), you don't have to perform the existence check yourself:

It turns out the dictionary's set indexer will do the check for you. All you need is

This applies to the .Net Dictionary<T,T>, SortedDictionary<T,T> and SortedList<T,T> implementations of IDictionary<T,T> .  But bear in mind that if you're coding to the abstraction IDictionary<T,T>, you can't guarantee that the specific implementation you're using will work this way.

No comments:

Post a Comment