Reputation: 1268
I have a Dictionary<Product, int> Inventory
which holds the inventory for the products that are in the shop.
How do I get the value that corresponds with the Product
and add 1 to it?
It is also possible that the Product
isn't in the dictionary.
Upvotes: 1
Views: 124
Reputation:
To deal with items that don't yet exist in your dictionary, my personally preferred way is to use TryGetValue
:
int stock;
inventory.TryGetValue(product, out stock);
inventory[product] = stock + 1;
This works because TryGetValue
sets stock
to default(int)
, which is 0
, if the product does not yet exist. 0
is exactly the value you want.
If you prefer to treat the stock
value as unassigned after TryGetValue
returns false
(for readability), then you can still use this same general approach:
int stock;
if (!inventory.TryGetValue(product, out stock))
stock = 0;
inventory[product] = stock + 1;
Upvotes: 2
Reputation: 63978
Something like this?
myDictionary[myProduct] += stockIncrease;
It's pretty much exactly the syntax as you would use to update an item in an array.
If it helps, think of it less in terms of "I want to the stock to go up" and more in terms of "how do I get the value that I need, and what can I do with that value".
If it's not guaranteed whether or not your product exists in your dictionary to begin with, then just add on an if-check:
if (!inventory.ContainsKey(myProduct)) {
inventory[myProduct] = 0;
}
inventory[myProduct] += stockIncrease;
Upvotes: 3