Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a function the .NET framework that can evaluate a numeric expression contained in a string and return the result? F.e.:

string mystring = "3*(2+4)";
int result = EvaluateExpression(mystring);
Console.Writeln(result); // Outputs 18

Is there a standard framework function that you can replace my EvaluateExpression method with?

like image 954
sindre j Avatar asked Dec 02 '08 11:12

sindre j


3 Answers

If you want to evaluate a string expression use the below code snippet.

using System.Data;

DataTable dt = new DataTable();
var v = dt.Compute("3 * (2+4)","");
like image 72
Ramesh Sambari Avatar answered Oct 23 '22 23:10

Ramesh Sambari


Using the compiler to do implies memory leaks as the generated assemblies are loaded and never released. It's also less performant than using a real expression interpreter. For this purpose you can use Ncalc which is an open-source framework with this solely intent. You can also define your own variables and custom functions if the ones already included aren't enough.

Example:

Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
like image 85
Sébastien Ros - MSFT Avatar answered Oct 24 '22 01:10

Sébastien Ros - MSFT


Try this:

static double Evaluate(string expression) {
  var loDataTable = new DataTable();
  var loDataColumn = new DataColumn("Eval", typeof (double), expression);
  loDataTable.Columns.Add(loDataColumn);
  loDataTable.Rows.Add(0);
  return (double) (loDataTable.Rows[0]["Eval"]);
}
like image 51
pero Avatar answered Oct 24 '22 00:10

pero