Skip to content

Library usage C#

Maciej Klemarczyk edited this page Oct 22, 2021 · 3 revisions

Instruction

  1. Install library from the NuGet.org
  2. Create instance of PredicateExpression with your expression to evaluate
  3. Call Prepare method if you want to reuse the evaluation with different variables
  4. Call Evaluate method with or without passing dictionary with variables
  5. Capture result of Evaluate method which indicates if the predicate is True or False

Examples

Simple condition example

var exampleExpression = "{<, 42, 182}";
var engine = new PredicateExpression(exampleExpression);
// Optional step to parse the expression before evaluation
engine.Prepare();
bool result = engine.Evaluate();

Simple condition example with variable injection

var exampleExpression = "{AND {<, $userId, 182}, {=, logged, $status}}";
exampleExpression = exampleExpression.Replace("$userId", "42");
exampleExpression = exampleExpression.Replace("$status", "logged");

var engine = new PredicateExpression(exampleExpression);
// Optional step to parse the expression before evaluation
engine.Prepare();
bool result = engine.Evaluate();

Simple condition example with variable evaluation

// Dictionary with all required variables
var variables = new Dictionary<string, object>();
variables["userId"] = 42;
variables["status"] = "logged";
variables["permission"] = 13;

var exampleExpression = "{AND {<, $userId, 182}, {=, logged, $status}, {HasFlag, $permission, 4}}";
var engine = new PredicateExpression(exampleExpression);
// Optional step to parse the expression before evaluation
engine.Prepare();
bool result = engine.Evaluate(variables);

Clone this wiki locally