If I have this situation:
public List<string> plants = new List<string>();
plants.Add("Lily");
plants.Add("Orange tree");
plants.Add("Raspberry");
plants.Add("Bell pepper");
plants.Add("Orange tree");
And I want to find the index of “Orange tree” using:
print(plants.IndexOf("Orange tree"))
it finds it as 1, because it stops at the first occurance, but if I do this: print(plants.IndexOf("Orange tree", 2))
it prints 4 because I started at index 2. What I’m trying to say is that both index 1 and index 4 are suitable as a search for “Orange tree”;
How ever if I have this situation:
public enum PlantType{
Tree, Flower, Bush, Vegetable
}
public class Plant{
public string name;
public PlantType type;
public string latinName;
public int rarity;
//constructor
public Plant(string _name, PlantType _type, string _latinName, int _rarity){
name=_name;type=_type;latinName=_latinName;rarity=_rarity;
}
}
List<Plant> plants = new List<Plant>();
plants.Add(new Plant("Lily", PlantType.Flower, "Lilium", 2));
plants.Add(new Plant("Orange tree", PlantType.Tree, "Citrus sinensis", 4));
plants.Add(new Plant("Raspberry", PlantType.Bush, "Rubus", 5));
plants.Add(new Plant("Bell pepper", PlantType.Vegetable, "Capsicum annuum", 5));
plants.Add(new Plant("Orange tree", PlantType.Tree, "Citrus sinensis", 4));
//When I search this, it gives me -1, so it seems it doesn't search for values, but for the memory address of the instance of the Plant class
plants.IndexOf(new Plant("Orange tree", PlantType.Tree, "Citrus sinensis", 4));
I can do something like this:
public class Plant{
//...fields, constructor, enum, etc.
public static int FindIndexOfPlant(List<Plant> plantList, string name, PlantType type){
int i = 0;
foreach(Plant plant in plantList){
if(plant.name.Equals(name) && plant.type == type) return i;
i++;
}
return -1;
}
}
print(Plant.FindIndexOfPlant(plants, "Orange tree", PlantType.Tree));
This seems messy