using System.Collections.Generic;
using System.Linq.Expressions;
static Expression BuildExpr<T>(Rule r, ParameterExpression param)
var left = MemberExpression.Property(param, r.MemberName);
var tProp = typeof (T).GetProperty(r.MemberName).PropertyType;
if (ExpressionType.TryParse(r.Operator, out tBinary))
var right = Expression.Constant(Convert.ChangeType(r.TargetValue, tProp));
return Expression.MakeBinary(tBinary, left, right);
var method = tProp.GetMethod(r.Operator);
var tParam = method.GetParameters()[0].ParameterType;
var right = Expression.Constant(Convert.ChangeType(r.TargetValue, tParam));
return Expression.Call(left, method, right);
public static void Main()
List<Rule> rules = new List<Rule>
new Rule("Age", "GreaterThan", "20"), new Rule("Name", "Equal", "John")}
var rule = new Rule("Age", "GreaterThan", "20");
Func<User, bool> compiledRule = CompileRule<User>(rule);
compiledRule(user2).Dump();
public static Func<T, bool> CompileRule<T>(Rule r)
var paramUser = Expression.Parameter(typeof (User));
Expression expr = BuildExpr<T>(r, paramUser);
return Expression.Lambda<Func<T, bool>>(expr, paramUser).Compile();
public string TargetValue
public Rule(string MemberName, string Operator, string TargetValue)
this.MemberName = MemberName;
this.Operator = Operator;
this.TargetValue = TargetValue;