Evaluating a mathematical expression

2019-09-09 16:50发布

问题:

Guys I am up with evaluating a string mathematical expression.

First I imported the library

using System.Linq.Expressions;

Then in my codes I did,

Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
  double result = e.Evaluate();

however I get the error as Cannot create an instance of the abstract class or interface 'System.Linq.Expressions.Expression'

Why the above is not working?

How can I evaluate this ?

回答1:

In order to evaluate expressions like this in c#, you have to use Roslyn. Here's an example (I changed a piece of code take from here http://blogs.msdn.com/b/csharpfaq/archive/2011/12/02/introduction-to-the-roslyn-scripting-api.aspx):

using Roslyn.Scripting.CSharp;

namespace RoslynScriptingDemo {
    class Program {
        static void Main(string[] args)        {
            var engine = new ScriptEngine();
            engine.Execute(@"System.Console.WriteLine((450*5)+((3.14*7)/50)*100);");
        }
    }
}

Expressions only let you to create a syntax tree from code:

Expression<Func<int,int,int>> add = (x, y) => x + y;
var res = add.Compilie()(2,3);

So you can't use string as a source for expression, you have to write it as a valid c# code.



回答2:

Try to use NCalc:

Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
double result = e.Evaluate();

http://ncalc.codeplex.com/



回答3:

I went for Ncalc. I am posting my codes for future users who will be on same problems like me.

1.Download the Ncalc(Binaries)http://ncalc.codeplex.com/releases/view/73656

  1. Reference the dll in your solution.(Right click > add reference > Browse > NCalc.dll)
  2. In codes

    Using NCalc;

3.May be used as

public Double Calculate(string argExpression)
        {
            //get the user passed string
            string ExpressionToEvaluate = argExpression;
            //pass string in the evaluation object declaration.
            Expression z = new Expression(ExpressionToEvaluate);
            //command to evaluate the value of the **************string expression
            var result = z.Evaluate();
            Double results = Convert.ToDouble(result.ToString());

            return results;

        }


回答4:

You can use Mathos Parser. It is a simple .NET Mathematical Expression parser.