.net dictionary and lookup add / update
- by freddy smith
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)