From the discussion / answer here: http://ncalc.codeplex.com/discussions/360990
The implementation that I tested and works (for your provided sample expression) is to implement the LogicalExpressionVisitor and write its parameters as they are found:
class ParameterExtractionVisitor : LogicalExpressionVisitor { public HashSet<string> Parameters = new HashSet<string>(); public override void Visit(NCalc.Domain.Identifier function) {
Then you will use it like:
var expression = NCalc.Expression.Compile("2 * [x] ^ 2 + 5 * [y]", false); ParameterExtractionVisitor visitor = new ParameterExtractionVisitor(); expression.Accept(visitor); var extractedParameters = visitor.Parameters; foreach (var param in extractedParameters) Console.WriteLine(param);
This prints for me "x" and "y".
Pay attention to the use of HashSet in ParameterExtractionVisitor . This is because if your expression contains the same variable more than once (for example: "[x] + [x]" ), it will be added twice. If you want to keep a record every time the same variable is used, replace the HashSet with List .
That being said, I have very little experience with NCalc, so my implementation of the redefined LogicalExpressionVisitor methods is a LogicalExpressionVisitor . When I inverted the void Visit(ValueExpression expression) method with expression.Accept(this) , this led to a StackOverflowException . So I just left the implementation empty and seemed to work. Therefore, I would advise you to take my answer here with a very large amount of salt. Your mileage may vary, and I cannot say if this works for all types of expressions.
Chris sinclair
source share