Duplicates in Dictionary

If one needs to fill dictionary with bunch of keys while tracking only last value for each, a generic inner loop code might looks something like this:

if (dict.ContainsKey(key)) {
dict[key] = value;
} else {
dict.Add(key, value);

Code checks if key exists, if not it is added; otherwise the old value is replaced. Pretty straightforward.

Surprisingly, this code can be simplified - a lot:

dict[key] = value;

Dictionary's indexed property will do exactly the same thing as code above - but in less lines.

Leave a Reply

Your email address will not be published. Required fields are marked *