Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Collections Sets and Dictionaries The System.Collections.Generic Namespace

evanpavan
evanpavan
5,025 Points

For the previous code challenge I'm stuck at "Bummer: The given key was not present in the dictionary."

I'm getting the following error from the code challenge Bummer: The given key was not present in the dictionary. I'm not sure what to do here as the error seems wrong. I'm declaring the AddWord method and using the variable word passed in the parameter to find the WordCount int value. The variable word shouldn't be tested against the Dictionary to see if it's a key because it's an undefined variable in the current context, and the Dictionary is null for all I know.

Here's my code. Pretty straight forward. I've added the following to the given AddWord method.

 WordCount[word]++; 

Here's the full code:

using System.Collections.Generic;

namespace Treehouse.CodeChallenges
{
    public class LexicalAnalysis
    {
        public Dictionary<string, int> WordCount = new Dictionary<string, int>();

        public void AddWord(string word)
        {
            WordCount[word]++; 
        }
    }
}
evanpavan
evanpavan
5,025 Points

Here's the solution: What the error must have mean't by key does not exist is that the method we are creating needs to have additional code to handle the scenario when the key passed does not exist in the dictionary

Added an if and TryGetValue

        public void AddWord(string word)
        {
            int value;
            if(WordCount.TryGetValue(word, out value))
            {
                WordCount[word]++;
            }
            else
            {
                WordCount.Add(word, 1);
            }
         }   

1 Answer

public class LexicalAnalysis { public Dictionary<string, int> WordCount = new Dictionary<string, int>();

    public void AddWord(string word)
    {
        if(WordCount.ContainsKey(word))
        {
            WordCount[word] = WordCount[word] + 1;
        }
        else
        {
            WordCount.Add(word, 1);   
        }
    }