I find myself writing this quite frequently.
Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
if (!h.Contains(key))
{
h.Add(key, value);
}
Is there a native method (perhaps something like AddIf() ??) that checks to see if it exists in the collection and if it does not, adds it to the collection? So then my example would change to:
Hashtable h = new Hashtable();
string key = "hahahahaahaha";
string value = "this value";
h.AddIf(key, value);
This would apply beyond a Hastable. Basically any collection that has a .Add method.
EDIT: Updated to add a value when adding to the Hashtable 🙂
Well, you probably don’t write that code, because
Hashtableuses key/value pairs, not just keys.If you’re using .NET 3.5 or higher, I suggest you use
HashSet<T>, and then you can just unconditionally callAdd– the return value will indicate whether it was actually added or not.EDIT: Okay, now we know you’re talking about key/value pairs – there’s nothing built-in for a conditional add (well, there is in
ConcurrentDictionaryIIRC, but…), but if you’re happy to overwrite the existing value, you can just use the indexer:Unlike
Add, that won’t throw an exception if there’s already an entry for the key – it’ll just overwrite it.