- Home /
Search for the index in an array of a customised class
I need to find the index of a customised class using only a value in one of the three values that I stored in the class.
city = new City[34];
city[0] = new City("Basilus", 1000, 2834);
city[1] = new City("Gortz", 3000,2455);
city[2] = new City("Daniz", 4500,1768);
I want to use the right most value to search for its index.
The City class looks like this:
public class City{
string cityName;
int cityPopulation;
int cityCoords;
public City(string cityName,int cityPopulation,int cityCoords)
{
this.cityName = cityName;
this.cityPopulation = cityPopulation;
this.cityCoords = cityCoords;
}
public string CityName()
{
return this.cityName;
}
public int CityPopulation()
{
return this.cityPopulation;
}
public int CityCoords()
{
return this.cityCoords;
}
}
I tried using the indexOf code but it wont work on this one because I need it to be a method for it to return a value. I've tried to create a function that will loop the array until it gets the correct index but it's saying " use of unassigned local variable 'index' ".
int GetIndexUsingCoords(int hexCoords)
{
int index;
for (int t = 0; t < 34; t++)
{
if (hexCoords == DefaultCityData.city[t].CityCoords())
{
index = t;
}
}
return index;
}
Is there a way to search for the index directly without using a loop or I will need to stick with the loop but just change some parts. Please help out, I've been working on it for the last couple of hours.
Implementation note on the City class: Those fields and getter methods look like good candidates for being turned into readonly fields, or properties:
public class City{
public string CityName {get; private set;}
public int CityPopulation {get; private set;}
public int CityCoords {get; private set;}
public City(string cityName,int cityPopulation,int cityCoords)
{
CityName = cityName;
CityPopulation = cityPopulation;
CityCoords = cityCoords;
}
}
Answer by Jwizard93 · Jul 09, 2017 at 02:02 AM
Looks fine to me except you need to initialize it to something. There's a chance no city is found with the correct hexCoords. In that case what is being returned?
At the top set index = -1.
That way the caller can see if the index came out to be between 0 and 34. Otherwise it can disregard it or throw an error or anything.
Alternatively use a list instead of an array and there will be more functionality already built in.
Lol, the answer was so simple. I set index to -1 and it worked.
I changed my array into list then tried to search for it.
int cityIndex = DefaultCityData.city.IndexOf(hexCoord);
but this line of code will not work it says, cannot convert hexCoord from int to city. What else am I missing on this line of code? I just want to search for the index using the 3rd value in the list.
After digging through some list codes. I found the answer that I needed.
Debug.Log(city.FindIndex(x => x.CityCoords() == 5769));
Thanks a lot for the suggestion to convert it to list! :)