Skip to content

Instantly share code, notes, and snippets.

@csuzw
Last active Aug 29, 2015
Embed
What would you like to do?
Dynamic Predicates
// using DynamicLinq
public static Func<TInput, TOutput> GetFuncFromLinq<TInput, TOutput>(this string predicate)
{
if (string.IsNullOrWhiteSpace(predicate)) return null;
LambdaExpression expression = DynamicExpression.ParseLambda(typeof(TInput), typeof(TOutput), predicate);
Func<TInput, TOutput> func = x => (TOutput)expression.Compile().DynamicInvoke(x);
return func;
}
// using CS-Script
public static Func<dynamic, bool> GetFuncFromScript(this string predicate)
{
if (string.IsNullOrWhiteSpace(predicate)) return null;
string scriptText = @"bool GetPredicate(dynamic e) { return " + predicate + "; }";
Func<dynamic, bool> result = CSScript.Evaluator.LoadDelegate<Func<dynamic, bool>>(scriptText);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment