Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to object in for loop

Tags:

c#

oop

loops

Let's say I have an object MyCharacter of the class Character, which has the following properties: Health, Mana, MoveSpeed.
From a different method I get a string that contains these stats as follows:
"Health: 100 Mana: 100 MoveSpeed: 100"
I now want to assign these stats to my object. My current attempt is this:

// stats is the string I showed above
var statsArray = stats.Split(' ');
for (var i = 0; i < statsArray.Length; i++)
{
    switch(statsArray[i])
    {
        default:
            break;
        case "Health:":
            MyCharacter.Health = statsArray[i+1];
            break;
        case "Mana:":
            MyCharacter.Mana = statsArray[i+1];
            break;
        case "MoveSpeed:":
            MyCharacter.MoveSpeed = statsArray[i+1];
            break;
    }
}

The thing now is, that I know the order of the stats. It's always Health, then Mana, then MoveSpeed. So I am looking for a way to simplify it, namely getting rid of this switch (since the actual Character here has 18 stats and it's not exactly good looking as it is).
My idea would be going through the array and tell the program to assign the first number it finds to Health, the second to Mana and the third to MoveSpeed.
Is anything like that even possible?

like image 541
Wilsu Avatar asked Nov 16 '15 09:11

Wilsu


People also ask

Which method do we use to loop an object js?

keys() method. The Object. keys() method was introduced in ES6. It takes the object we want to loop over as an argument and returns an array containing all property names (also known as keys).


1 Answers

Since you know the exact format, you can just access the indexes directly:

string stats = "Health: 100 Mana: 100 MoveSpeed: 100";

var statsArray = stats.Split(' ');
MyCharacter.Health = statsArray[1];
MyCharacter.Mana = statsArray[3];
MyCharacter.MoveSpeed = statsArray[5];

You could also use a regular expression for this, which has the benefit that it further validates your pattern (so if there is a case that does not match your format, you get an exception):

var m = Regex.Match(stats, @"Health: (\d+) Mana: (\d+) MoveSpeed: (\d+)");

MyCharacter.Health = m.Groups[1].Value;
MyCharacter.Mana = m.Groups[2].Value;
MyCharacter.MoveSpeed = m.Groups[3].Value;

Note: You probably want those properties to contain integers so you can calculate with the values, so you should call int.Parse() on each of the values.

like image 155
poke Avatar answered Oct 13 '22 00:10

poke