Lambda Compilation
Using the concept of lambda compilation, NCalc can convert a LogicalExpression object to an anonymous function. Using this you can write complex functions and even have greater performance when evaluating the expression.
Especial thanks to the NCalc2 fork for the original implementation.
Getting Started
First, you will need to add a reference to NCalc.LambdaCompilation to your project.
Functionalities
Simple Expressions
var expression = new Expression("1 + 2");
Func<int> function = expression.ToLambda<int>();
Debug.Assert(function()); //3
Expressions with Functions and Parameters
class Context
{
public int Param1 { get; set; }
public string Param2 { get; set; }
public int Foo(int a, int b)
{
return a + b;
}
}
var expression = new Expression("Foo([Param1], 2) = 4 && [Param2] = 'test'");
Func<Context, bool> function = expression.ToLambda<Context, bool>();
var context = new Context { Param1 = 2, Param2 = "test" };
Debug.Assert(function(context)); //true
Compatibility
Since v5.5 by default NCalc uses a FastExpressionCompiler
to improve the compilation performance (which is 10-40x times faster than .Compile()). But if you face issues, you can switch back to the built-in System.Linq.Expressions.Compile() method by using the AppContext switch:
AppContext.SetSwitch("NCalc.UseSystemLinqCompiler", true)
Performance
You should cache the result of Expression.ToLambda<T>(). Evaluation is faster, but compiling the lambda is still expensive.
See benchmarks for more info.