Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing value for key which is existing in dictionary

Tags:

c#

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);
           }
        }
like image 517
Vlad Avatar asked Jan 29 '26 21:01

Vlad


2 Answers

You need to use the indexer property:

if (!concordanceDictionary.ContainsKey(word))
{
    concordanceDictionary.Add(word, 1);
}
else
{
    concordanceDictionary[word]++;
}
like image 199
Dmitry Avatar answered Feb 01 '26 09:02

Dmitry


just do

else
{
    concordanceDictionary[word]++;
}
like image 24
Stewart_R Avatar answered Feb 01 '26 09:02

Stewart_R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!