1

I am trying to evaluate expressions that are inputted as strings

example: string svar1="1 * 2 * 3";

I need to be able to evaluate that to answer 6.

I am thinking about parsing it by spaces, then match the operators with switch to each functions (need to do +,-,*,/,%, etc) but it seems like a very tedious way as there are so many operators to code. Is there a way to convert a char/string containing an operator into actual operator?

tom
  • 445
  • 4
  • 20

4 Answers4

4

one easy way is to use DataTable.Compute Method

    static void Main(string[] args)
    {
        DataTable table = new DataTable();

        var result = table.Compute("1 * 2 * 3","");
    }
Fredou
  • 19,848
  • 10
  • 58
  • 113
  • 2
    An interesting, if not completely abusive and hacked, approach. This may not work for more *complex* expressions. – BradleyDotNET Feb 13 '15 at 20:19
  • @BradleyDotNET, I don't know the limit of it but you always need to test to make sure you get want you want :-) – Fredou Feb 13 '15 at 20:21
  • @BradleyDotNET: Abusive in the sense of using an elephant gun to kill a flea. Not hacked at all -- parsing and evaluating mathematical expressions is a core requirement of the `Compute` method. There's just additional ability for those expressions to include field accesses which won't be used here. – Ben Voigt Feb 13 '15 at 20:23
  • How does this satisfy the documented requirement that "the expression parameter requires an aggregate function" ? – Ben Voigt Feb 13 '15 at 20:25
  • @BenVoigt 1 and 2 and 3 are actually 3 aggregated values – Fredou Feb 13 '15 at 20:26
1

No, this functionality is not included in any standard .NET assembly. Your method, in addition to being tedious, is going to be error prone.

You are looking for a math expression parser, NCalc is one such library.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
0

Looks like a library called NCalc can accomplish what you need.

Evaluating string "3*(4+2)" yield int 18

Community
  • 1
  • 1
John M Fecko
  • 105
  • 5
0

If you want some insight/code to demonstrate how this is done properly, using correct rules of precedence, in C# this is a good sequence of articles:

http://ericwhite.com/blog/map/recursive-descent-parser/

James Gaunt
  • 14,631
  • 2
  • 39
  • 57