Everyday you learn something new. You do. That is if you let yourself to be taught everyday.
I didn't know that you could solve this expression string in .NET in one line of code:
"4 + 5 + 10 - 4 / 5 * 2"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace KeithRull.SimpleExpressionCalculator
{
class Program
{
static void Main(string[] args)
{
string expressionToEvaluate = "4 + 5 + 10 - 4 / 5 * 2";
var result = new DataTable().Compute(expressionToEvaluate, null);
Console.Write(result);
Console.Read();
}
}
}
The result is 17.4. Nifty huh? You can also group the expressions to display a clearer evaluation instruction and it still will work.
string expressionToEvaluate = "(((4 + 5) + (10 - 4)) / 5) * 2"; //will result to 6This is all cool but there's a gotcha. DataTable.Compute() method can only evaluate simple expressions so your
string expressionToEvaluate
= "Tan(10) * 2"; //errorWould throw an exception of type EvaluateException because it could not recognize the function Tan().
One solution you could take to solve this problem is to use a dynamic language in the DLR like IronRuby or IronPython.
namespace KeithRull.SimpleExpressionCalculator
{
class Program
{
static void Main(string[] args)
{
string expressionToEvaluate = "Tan(20) * 2";
var p = new IronPython.Hosting.PythonEngine();
var result = p.EvaluateAs<double>(expressionToEvaluate);
Console.Write(result);
Console.Read();
//will output: 4.47432188844948
}
}
}
You can check out
Kirill Osenkov's post for more info regarding this approach.
Another way which i think is the better way is using a third-party library that already support this like
NCalc.
NCalc is an open source Mathematical Expression Evaluator for .NET that can parse any expression and evaluate the result, including static or dynamic parameters and custom functions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using NCalc;
namespace KeithRull.SimpleExpressionCalculator
{
class Program
{
static void Main(string[] args)
{
string expressionToEvaluate = "Tan(20) * 2";
Expression e = new Expression(expressionToEvaluate);
var result = e.Evaluate();
Console.Write(result);
Console.Read();
//will output: 4.47432188844948
}
}
}Pretty cool huh?!