Apr 212017

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.