.net dictionary and lookup add / update

As Evgeny says, the indexer will already replace existing values – so if you just want to unconditionally set the value for a given key, you can do

dictionary[key] = value;

The more interesting case is the “get a value, or insert it if necessary”. It’s easy to do with an extension method:

public static TValue GetOrCreateValue<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     TValue value)
{
    return dictionary.GetOrCreateValue(key, () => value);
}

public static TValue GetOrCreateValue<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary,
     TKey key,
     Func<TValue> valueProvider)
{
    TValue ret;
    if (!dictionary.TryGetValue(key, out ret))
    {
        ret = valueProvider();
        dictionary[key] = ret;
    }
    return ret;
}

Note the use of a delegate to create the default value – that facilitates scenarios like the “list as value” one; you don’t want to create the empty list unless you have to:

dict.GetOrCreateValue(key, () => new List<int>()).Add(item);

Also note how this only performs the lookup once if the key is already present – there’s no need to do a ContainsKey and then look up the value. It still requires two lookups when it’s creating the new value though.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)