I am sick of doing blocks of code like this for various bits of code I have:
if (dict.ContainsKey[key]) {
dict[key] = value;
}
else {
dict.Add(key,value);
}
and for lookups (i.e. key -> list of value)
if (lookup.ContainsKey[key]) {
lookup[key].Add(value);
}
else {
lookup.Add(new List<valuetype>);
lookup[key].Add(value);
}
Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are?
e.g.
dict.AddOrUpdate(key,value)
lookup.AddOrUpdate(key,value)
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
The more interesting case is the “get a value, or insert it if necessary”. It’s easy to do with an extension method:
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:
Also note how this only performs the lookup once if the key is already present – there’s no need to do a
ContainsKeyand then look up the value. It still requires two lookups when it’s creating the new value though.