Reputation: 31
I am creating a web project in which user enters some filter criteria and data are rendered to a grid. The criteria will be passed to a Rest Service and will be based on properties defined in the model classes defined on the server.
Example: let's assume that the service returns chocolates and the user requests something like below:
((ChocolateColor == DarkBlack) || (ChocolateColor == White) &&
ChocolatePrice > 1.5 Euros) || ChocolateOwner == "ChocoMan"
I want to be able to extract the filter runtime and convert it to a filter against my model classes. Instead of creating tons of code parsing the filter is there more clever way to apply my filters ?
The filters will be given directly as boolean expressions or will be constructed by using a GUI.
Upvotes: 0
Views: 916
Reputation: 5847
I think that tons of code are actually required, but maybe someone did that already for you. There were multiple attempts to implement dynamic expression evaluators, and I personally didn't test any, but here is an example: https://netmatze.wordpress.com/2013/03/04/implementing-expression-evaluator-in-c/
From the example, it's possible to do something like this:
Person person = new Person() { Name = "Mathias", Age = 36, Children = 2, Married = true };
var ruleText = " (Children = 2 && Married = true) || Age > 36 ";
Evaluator evaluator = new Evaluator();
var evaluatorResult = evaluator.Evaluate<Person>(ruleText, person);
Now, that looks like you could use this engine and adapt to your requirements, but that possibly being a "path of trial and tribulation".
Also that's still far from any keywords you gave (like linq or rest). When you use the Entity Framework work on the backend as an example, that won't work, because this commands canno be converted to SQL - and you don't want to code that.
Upvotes: 2