0

My program currently loads a csv file and converts each line to different strings and int values. The problem is, while I can easily convert a simple number, it needs to be able to convert an equation with variables.

My current code for this is -

string[] values = line.Split(new string[] { "," }, StringSplitOptions.None)
                    .Select(p => p.Trim()).ToArray();
                if (values.Length != 8) continue;

                var species = new SpeciesClasses()
                {
                    Species = values[0],
                    Description= values[1],
                    Strength = int.Parse(values[2]),
                    Intelligence = int.Parse(values[3]),
                    Dexerity = int.Parse(values[4]),
                    Charisma = int.Parse(values[5]),
                    Endurance = int.Parse(values[6]),
                    Initiative = int.Parse(values[7]),

                };

And my csv file is

Pilot, Trained to handle all vehicle types., 0, 6, 0, 0, 0, 0
Medic, Trained to cure and heal others., 0, 0, 5, 0, 0, 0

Which works fine, now the tricky part is a line like this -

Berzerker, The closer to death this crew gets - the stronger they hit., (15-HP)/4, 0, 0, 0, 0, 0
Focused, Using their mass intellect - this crew can aim more accurately., 0, 0, INTEL, 0, 0, 0

So I not only need to convert the string to an int equation with different variables - in this case an HP and INTEL int.

Hugo Sereno Ferreira
  • 8,600
  • 7
  • 46
  • 92
  • This isn't possible with normal C# (without writing a custom parser/grammar). Have you looked at Roslyn? There *is* a run-time compilation library out there somewhere, but I don't remember the name...\ – BradleyDotNET Jul 10 '14 at 17:38
  • Do you know all the possible options as in is HP and Intel the only ones – rerun Jul 10 '14 at 17:38
  • You need an expression parser. A question regarding that can be found [here](http://stackoverflow.com/questions/4392022/i-need-a-fast-runtime-expression-parser). – user3820547 Jul 10 '14 at 17:38
  • possible duplicate of [Best Free C# Math Parser using variables, user defined functions, custom operators](http://stackoverflow.com/questions/5312225/best-free-c-sharp-math-parser-using-variables-user-defined-functions-custom-op) – Ian Mercer Jul 10 '14 at 17:39

1 Answers1

0

If int.Parse() fails (btw try int.TryParse(...)) fallback to a more specialized tool:

More info here: Equation (expression) parser with precedence?

Community
  • 1
  • 1
Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65