C
C#7mo ago
mack

Finding Index of Dictionary Key

hey guys, just joined the server so forgive me if im not asking in the right place... please direct me elsewhere if this isnt the right area i am making an inventory system using a Dictionary<int, int> (key is for item ID, value is for how many of that item you have) and i was just curious about something:
if (GameDataManager.Instance.inv.ContainsKey(ID))
{
// get index of key ID
}
if (GameDataManager.Instance.inv.ContainsKey(ID))
{
// get index of key ID
}
does that make sense? i want to know if ID is already in inv so that, if it is, i add 1 to the value, and if not, i Add() the ID
4 Replies
Keswiik
Keswiik7mo ago
First off, I see no reason to find the 'index' of your item if you're using a dictionary. The entire point is to retrieve and set values using whatever identifier you've chosen. In this case it would be the item ID.
Keswiik
Keswiik7mo ago
this will let you 1) attempt to load the value, returning a bool to indicate success 2) assign the retrieved value to the out field you declare
Pobiega
Pobiega7mo ago
I would also suggest making an extension method for Dictionary<T, int> like "Increment` that creates the key and sets the value to 1 if called with a non-existing key. that makes your inventorycode trivial
Want results from more Discord servers?
Add your server