Efficiency problem during foreach cycle
I have this code, which I think is not very efficient since it checks for the current Language for every item in the list:
foreach (InfoSpecies c in list.Especies) //list has 37 items
{
if (Localization.Instance.CurrentLanguage == SystemLanguage.Portuguese)
{
nomeComum = c.NomeComum;
}
else
{
nomeComum = c.CommonName;
}
//do something with nomeComum
}
I'm trying to change the code in order to perform the test only once, just before running the foreach cycle. I think it has to be something like this:
if (Localization.Instance.CurrentLanguage == SystemLanguage.Portuguese)
{
nomeComum = c.NomeComum;
}
else
{
nomeComum = c.CommonName;
}
foreach (InfoSpecies c in list.Especies)
{
//do something with nomeComum
}
But this is obviously not working, since c.NomeComum will only exist during the foreach cycle. Is there a way to pass the apropriate assignment after the if cycle has run, in order for the right item to be selected from the list? Can someone help me? Thanks
Answer by exzizt · Mar 25, 2018 at 10:01 PM
If c.NomeComum is the same for each element in the list, you can do:
nomeComum = list.Especies[0]; // This gets the first element from the list (there must be one!).
// Now go through your foreach.
Thank you for your answer exzizt, but unfortunately, nomeComum is always different.
The purpose of the foreach cycle is to populate a scrollable list that receives its elements from a JSON file containing a list of marine species, depicted by their scientific name and their English and Portuguese equivalents. And the reason for the if cycle is to figure it out if the system language is in English or Portuguese, thus presenting the species name in the appropriate language (i.e., c.CommonName or c.NomeComum from the JSON).
Everything is fine and working, but I think that the way I have my code, it's not the most efficient way to do this. I mean there are 37 species in the list, and the current code checks for the system language each time a species is added to the scrollable list.
I could simply put the foreach cycle inside each of the if else statements, and then changing the nomeComum assignment, thus solving my problem. But the foreach cycle is much more extensive than the one shown here, and since the only thing changing would be the nomeComum assignment, almost 98% of the foreach code would be duplicate in each of the the if else statements. I think there is no need for this redundancy, there must be other way...
If it's always different for each item in the loop, then you have to check it for each item in the loop.
Your answer
Follow this Question
Related Questions
Dialogue Skipping Issues? 0 Answers
Spawning multiple gameobjects with random scales 2 Answers
Iterating through a custom keycode enum for input detection 1 Answer
How to flip 2D object, mine isnt working nor any others i can find. 1 Answer
Add changeable conditions in the editor, similar to unityEvent? 0 Answers