Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Toxic-Cookie opened this issue Nov 6, 2021 · 1 comment
Open

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

Toxic-Cookie opened this issue Nov 6, 2021 · 1 comment
Labels

Comments

@Toxic-Cookie
Copy link

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
Copy link
Owner

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 :

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants