Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Collections Sets and Dictionaries Using Dictionaries

Calvin Secrest
Calvin Secrest
24,815 Points

An item with the same key has already been added.

BUMMER! An item with the same key has already been added.

Code the AddWord method such that, WordCount will contain the number of times the AddWord method has been called with a given word.

For example, if AddWord is called twice with the word "rock" then WordCount["rock"] will be 2.

Please help...

LexicalAnalysis.cs
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.Add(word, (WordCount.Count +1));
        }
    }
}

2 Answers

Steven Parker
Steven Parker
231,248 Points

:point_right: Keys in a dictionary must all be unique.

Your code should check to see if a word has already been added, and only add a new one if it's not already there. If it is already there, you can just modify the value.

Joel Brennan
Joel Brennan
18,300 Points

I found this answer very helpful for solving this question: http://stackoverflow.com/a/7132978