kkakroo
kkakroo

Reputation: 1113

Dictionary.ContainsValue() always returning true

I have a dictionary of all alphabets mapped to morse code

Dictionary<string, string> data = new Dictionary<string, string>();
        data.Add("a", ".-");
        data.Add("b", "-...");
        data.Add("c", "-.-.");
        data.Add("d", "-..");
        data.Add("e", ".");
        data.Add("f", "..-.");
        data.Add("g", "--.");
        data.Add("h", "....");
        data.Add("i", "..");
        data.Add("j", ".---");
        data.Add("k", "-.-");
        data.Add("l", ".-..");
        data.Add("m", "--");
        data.Add("n", "-.");
        data.Add("o", "---"); and so on..

I'm trying to check on a condition if the substring of an existing morse code exists in the dictionary or not.

 foreach (var item in arraylist)
        {

            int smallcount=0;
            int startIndex = 0;
            //check if this combination exists for morse code
            for(int w=0;w<shortInput;w++)
            {
                int substringLength=Convert.ToInt32(item[w].ToString());
                string sub = morsecode.Substring(startIndex, substringLength);
                if (data.ContainsValue(sub)) ; 
                {
                    smallcount++;

                }
                startIndex = startIndex + substringLength;
            }

            if(smallcount==shortInput)
            { count++; }


        }

Here data.ContainsValue(sub) always returns true even if the value does not exist in the dictionary. Code Snapshot

Can anyone tell me if i'm missing anything.?

Upvotes: 3

Views: 109

Answers (1)

yaakov
yaakov

Reputation: 5851

ContainsValue is not actually returning true, however you have a stray semicolon after the if statement. This means that the following block will always be executed, as it is not executed conditionally. It gets treated as follows:

if (data.ContainsValue(sub))
{
}
{
    smallcount++;
}

Instead, remove the semicolon so that you actually have a block directly following the if statement, like so:

if (data.ContaisnValue(sub))
{
    smallcount++;
}

Upvotes: 6

Related Questions