0

If I have a user give a string such as

eval= "productId = '100' and (GUID = '100' or (GUID = '200' and productId = '100' ) )"

what would be the best way to use the string to see if a object in memory meets those constraints? For example the following model would evaluate true:

evaluate(eval, new Product{productId ='100', GUID='100'})

Anyone push me in the direction of a design pattern that could accomplish this?

1 Answers1

1

Using NCalc and reflection, an Evaluate method can be written like:

public object Evaluate(string exprString, object o)
{
    var dict = o.GetType().GetProperties().ToDictionary(p => p.Name, p => p);

    var expr = new NCalc.Expression(exprString);
    expr.EvaluateParameter += (name, e) =>
    {
        e.Result = dict[name].GetValue(o, null);
    };

    return expr.Evaluate();

}

var res = Evaluate(
             "productId = '100' and (GUID = '100' or (GUID = '200' and productId = '100' ) )", 
             new { productId = "100", GUID = "100" });

OR

var res2 = Evaluate("x + 100 + y", new { x = 10, y = 1 });

PS: Error checks + "public fields" of the given object are ignored for simplicity

Eser
  • 12,346
  • 1
  • 22
  • 32