C# dictionary and lookup add / update

Posted by freddy smith on Stack Overflow See other posts from Stack Overflow or by freddy smith
Published on 2010-04-12T07:11:46Z Indexed on 2010/04/12 7:13 UTC
Read the original article Hit count: 311

Filed under:
|

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);
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)

© Stack Overflow or respective owner

Related posts about c#

Related posts about collections