Vlad
Vlad

Reputation: 279

Increasing value for key which is existing in dictionary

I'm trying to create concordance. I have dictionary, where key - is word and value - is frequency of this word If word exist in dictionary I need to increase value for this word. I'm using ContainsKey to check if word exists, bot don't understand how to increase value

    string[] words = SplitWords(lines);

    foreach (var  word in words)
    {
            int i = 0;
            if (!concordanceDictionary.ContainsKey(word))
            {
                concordanceDictionary.Add(word, i);
            }
            else
            {

            }
            foreach (KeyValuePair<string, int> pair in concordanceDictionary)
            {
                Console.WriteLine("{0}:{1}",pair.Key, pair.Value);
           }
        }

Upvotes: 2

Views: 2147

Answers (3)

Steve
Steve

Reputation: 216243

If the test for ContainsKeys fails and after adding the key, just increment the value.
There is no need of the else block

string[] words = SplitWords(lines);
foreach (var  word in words)
{
    if (!concordanceDictionary.ContainsKey(word))
       concordanceDictionary.Add(word, 0);
    concordanceDictionary[word]++;
}

Upvotes: 0

Dmitry
Dmitry

Reputation: 14059

You need to use the indexer property:

if (!concordanceDictionary.ContainsKey(word))
{
    concordanceDictionary.Add(word, 1);
}
else
{
    concordanceDictionary[word]++;
}

Upvotes: 5

Stewart_R
Stewart_R

Reputation: 14485

just do

else
{
    concordanceDictionary[word]++;
}

Upvotes: 4

Related Questions