Hi,
I want to give each Item in my list ItemDatabase a name (I have a Name string in my Item class). How would I do this in C#?
I want to be able to call the function Add(); for another list like this:
Inventory.Add(Weapon);
Inventory.Add(Potion);
Hi there
If I understanding your question correctly, you effectively want to be able to do something like:
//this would be your 'inventory' type
Dictionary<string,InventoryItem> Inventory = new Dictionary<string,InventoryItem>();
//add items with a 'key' which is a string
Inventory.Add("weapon", Weapon);
Inventory.Add("potion", Potion);
//or maybe the items already have a 'name' member
Inventory.Add(Weapon.name, Weapon)
Inventory.Add(Potion.name, Potion)
//then you can find items like this:
InventoryItem theweaponitem = Inventory["weapon"];
The dictionary class is contained within the c# namespace ‘System.Collections.Generic’ (just like the list class. In its initial definition you specify the ‘key’ and the ‘value’ types. So here I’ve created a dictionary with a key type of ‘string’, with a value type of ‘value’.
It also has a few other useful functions to access the dictionary in different ways:
InventoryItem theitem;
//will try and get the weapon item, but raise an exception if it doesn't exist
theitem = Inventory["weapon"];
//will check if the item exists
if(Inventory.ContainsKey("weapon"))
{
//stuff that happens if weapon exists
}
//handy function to check the item exists AND get it as one operation (faster than using ContainsKey and then accessing it normally)
if(Inventory.TryGetValue("weapon",out theitem))
{
//stuff that happens if the weapon exists
}
//iterating over all values in the dictionary
foreach(InventoryItem item in Inventory.Values)
{
}
//iterating over all keys in the dictionary
foreach(string key in Inventory.Keys)
{
}
//iterating over all pairs of key/value in the dictionary
foreach(KeyValuePair<string,InventoryItem> pair in Inventory)
{
}
//I often find this pattern useful - for creating/adding a key if it doesn't exist, then returning it
InventoryItem CreateOrGetItem(string item_name)
{
InventoryItem result;
if(!Inventory.TryGetValue(item_name,out result))
{
result = new InventoryItem();
Inventory.Add(item_name,result);
}
return result;
}
Enjoy!
I haven’t checked it, but you can use dictionaries in C# (which basically are the same as maps). It would be something like:
Dictionary<string, Item> ItemDatabase = new Dictionary<string, Item>();