Lambda Compilation
Using the concept of lambda compilation, NCalc can convert a LogicalExpression object to an anonymous function. Using it, you can write complex functions and improve performance of expression evaluation.
Special thanks to the NCalc2 fork for the original implementation.
Lambda compilation is not available in the AOT version as these two features are mutually exclusive.
Functionality
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 built-in System.Linq.Expressions.Compile() method by using AppContext switch:
AppContext.SetSwitch("NCalc.UseSystemLinqCompiler", true)
Performance
You should cache the result of ToLambda<TResult>(CancellationToken). The evaluation of compiled expressions is faster, but the compilation of them is rather slow. See benchmarks for more info.
Limitations
Not all functionality is supported with Lambda compilation. Unsupported functionality includes loops, conditional statements, and indexed access to lists and strings.