C#: KeyNotFoundException: The given key was not present in the dictionary

1.9k views Asked by At
foreach (KeyValuePair<String, EngineProperty> kvp in propertyDict)
{
    Debug.Log(kvp.Key.GetType()+" : "+ kvp.Key+ " "+ mainText.text.GetType()+ " "+ mainText.text);
}
slider.value = propertyDict[mainText.text].GetSpeed();

5 items get printed from the foreach loop. The below code is one of them

System.String :   Piston   System.String   Piston

Piston is the key which I'm looking for

But right below the for loop,

when I use this

slider.value = propertyDict[mainText.text].GetSpeed();

I get this error

KeyNotFoundException: The given key was not present in the dictionary.

But key was printed in the for loop. I don't get it.
This is how I initialized

public Dictionary<String, EngineProperty> propertyDict = new Dictionary<String, EngineProperty>();

I have tried replacing everything with String with string, and still, it doesn't work.

What do I do?

1

There are 1 answers

0
Kyle W On BEST ANSWER

As Jon Skeet said in his comment, the issue looks to be extra spaces. If you look at the first part of the string System.String : Piston, there are 3 spaces between the colon and Piston, but you have only put one in your separator. That means there are 2 spaces at the beginning of Piston. Similarly, there are 3 after Piston, so that means the actual string is Piston . For the mainText, you have a similar 3 spaces before Piston, but none after, according to the string you posted. This would make mainText to be Piston, which doesn't match.