ExpressionEvaluator icon indicating copy to clipboard operation
ExpressionEvaluator copied to clipboard

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

Open Toxic-Cookie opened this issue 3 years ago • 1 comments

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?

Toxic-Cookie avatar Nov 06 '21 09:11 Toxic-Cookie

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 :

codingseb avatar Nov 10 '21 14:11 codingseb