KeyNotFoundException: The given key was not present in the dictionary

When ever i Call this Function i get the Error:

“KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.Int32,Item].get_Item (Int32 key)” on the line indicated by ****'s.


void CraftItem(int craftedItemID, int R1ID, int R2ID, int R1Amount, int R2Amount){
    		//Resource 1
    		for(int i = 0; i < PlayerInventory.Inventory.Count; i++){
    			if(PlayerInventory.Inventory_.ID == R1ID && PlayerInventory.Inventory*.currentStack >= R1Amount){*_

_ PlayerInventory.Inventory*.currentStack -= R1Amount;
} else if(PlayerInventory.Inventory.ID == R2ID && PlayerInventory.Inventory.currentStack >= R2Amount){
PlayerInventory.Inventory.currentStack -= R2Amount;
for(int cnt = 0; cnt < PlayerInventory.ItemDictionary.Count; cnt++){
if(PlayerInventory.ItemDictionary[cnt].ID == craftedItemID){**************
Item craftedItem = PlayerInventory.ItemDictionary[cnt];

Whats wrong with what i am doing?_

You are using a dictionary like it is a list: Change your dictionary to a List

The inventory (dictionary) count is the number of elements in the dictionary (keys) but the key values do not necessarily have the values 0…PlayerInventory.Inventory.Count

You’ll need to adjust all of your code to use the list as it’s supposed to be used.

Think about how the Dictionary class works - the key can be any arbitrary value in the key type range where as the List class’s index is an ordered set of values.

That is, the Dictionary keys can be any type (even strings) so there is no implied order.

You need to read up and understand the difference between a dictionary and a (generic) list in order to understand how they differ and when each is applicable.