When doing something like:
int value;
if (dict.TryGetValue(key, out value))
{
if (condition)
{
//value = 0; this copies by value so it doesn't change the existing value
dict[key] = 0;
}
}
else
{
dict[key] = 0;
}
Is there any way I can avoid index lookup to replace the existing value? I'm already verifying the key exists using TryGetValue
so it seems like a waste to have to retrieve value by index again.
On a separate note, as in the else{}
part of my code, is it generally considered good practice to use the indexer when adding new or replacing old values, and add to make it clear you are adding and not replacing? Or should I just use the indexer every time? The way I have learned to use dictionary, I always do a TryGetValue
lookup and in the else portion I handle cases where no key exists.
value
? – Benderif (!dict.TryGetValue(key, out value) || value > 0) { dict[key] = 0; }
you can usevalue
, because you'll only get past the||
if the TryGet worked. – Unweptdict.Add(key, 0)
overdict[key] = 0
in cases where you know thekey
is new. – Alvaalvan