Finding already existing value in Key Value pair

Olivarsham picture Olivarsham · Jan 23, 2013 · Viewed 78.6k times · Source

I am storing a string and int value in Key value pair.

var list = new List<KeyValuePair<string, int>>();

While adding i need to check if string(Key) already exists in list, if exists i need to add it to Value instead of adding new key.
How to check and add?

Answer

Habib picture Habib · Jan 23, 2013

Instead of List you can use Dictionary and check if it contains key then add the new value to the existing key

int newValue = 10;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
if (dictionary.ContainsKey("key"))
    dictionary["key"] = dictionary["key"] + newValue;