- Home /
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.
Code:
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[i].ID == R1ID && PlayerInventory.Inventory[i].currentStack >= R1Amount){
PlayerInventory.Inventory[i].currentStack -= R1Amount;
} else if(PlayerInventory.Inventory[i].ID == R2ID && PlayerInventory.Inventory[i].currentStack >= R2Amount){
PlayerInventory.Inventory[i].currentStack -= R2Amount;
}
}
for(int cnt = 0; cnt < PlayerInventory.ItemDictionary.Count; cnt++){
if(PlayerInventory.ItemDictionary[cnt].ID == craftedItemID){**************
Item craftedItem = PlayerInventory.ItemDictionary[cnt];
AddItem(craftedItem);
}
}
}
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
I change it to a List, but it has messed up ALOT, and i mean alot of my code :(
Answer by larku · Jan 01, 2014 at 11:56 PM
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.
Your answer
Follow this Question
Related Questions
iTween Paths : Element with the same key already exists in the dictionary 5 Answers
Dictionary wont give me value with correct key 1 Answer
Storing XML node and accessing from a dictionary 0 Answers
C# Auto Generated Key with Variable (Hash, Metadata, etc.) 2 Answers
The Given Key cannot be found in the Dictionary and I have no idea why. Worked perfectly before. 0 Answers