codingseb / ExpressionEvaluator

A Simple Math and Pseudo C# Expression Evaluator in One C# File. Can also execute small C# like scripts
MIT License
595 stars 99 forks source link

How do I convert a string into a Predicate<T>? #125

Open Toxic-Cookie opened 3 years ago

Toxic-Cookie commented 3 years ago

My goal is to convert a string into a predicate like so:

string = "x => x.Equals(1)";

Predicate<int> predicate = (Predicate<int>)ExpressionEvaluator.Evaluate(string);

Is this possible? If so how can I accomplish this?

codingseb commented 3 years ago

Hello @Toxic-Cookie. There is nothing in ExpressionEvaluator to return a compiled predicate or a other delegate. As everything is evaluate on the fly and do not compile. If you are not concern about performance you could encapsulate it like this :

string predicateText = "x.Equals(1)";

Predicate<int> predicate = x => (bool)(new ExpressionEvaluator(new {x=x}).Evaluate(predicateText));

Console.WriteLine(predicate(1)); // true
Console.WriteLine(predicate(5)); // false

Otherwise there are others libraries like DynamicExpresso that support this use case with better performances :