How can I get a value from a string with a variable name?

I have the following code:

var currentCity = db.City.Find(player.Location); switch (TravelTo) { case 1: costs = currentCity.TravelCost.City1; break; case 2: costs = currentCity.TravelCost.City2; break; case 3: costs = currentCity.TravelCost.City3; break; case 4: costs = currentCity.TravelCost.City4; break; case 5: costs = currentCity.TravelCost.City5; break; } 

Is there a better way to get value? Is there a way to change the name of the string I want to call? So I could create something like

 costs = currentCity.TravelCost.City[TravelTo] 

Or something like that? I feel like I wrote an unnecessary switch statement, but my knowledge of C # is not good enough to come up with an alternative.

Thanks,

+4
source share
3 answers

There really is no better way to give you those columns and City1..n property City1..n . But you could at least put this switch statement inside the TravelCost object. That is, you could have a public int TravelCost.GetCostByCity(int city) method that contained an unpleasant switch statement.

+2
source

I'm new to C # myself, and I don’t know exactly what data types each of them is. But the code itself looks great. I understand that TravelCost is an enumeration? If not, it is a great idea to make it this way. You can also use the dictionary to store and manage data. But for me it looks good enough

+2
source

You can use hashtable .

Try the following:

 Hashtable distancesFromCityTo = new Hashtable(); distancesFromCityTo.Add("City1", 1000); distancesFromCityTo.Add("City2", 450); int cost1 = (int)distancesFromCityTo["City1"]; int cost2 = (int)distancesFromCityTo["City2"]; 
+1
source

Source: https://habr.com/ru/post/1481154/


All Articles