How does PredicateBuilder work

Let’s say you have: Expression<Func<Person, bool>> isAdult = p1 => p1.Age >= 18; // I’ve given the parameter a different name to allow you to differentiate. Expression<Func<Person, bool>> isMale = p2 => p2.Gender == “Male”; And then combine them with PredicateBuilder var isAdultMale = isAdult.And(isMale); What PredicateBuilder produces is an expression that looks like this: … Read more

What does Expression.Reduce() do?

The document you need to look at is expr-tree-spec.pdf. This is the specification for the expression trees. Read the “2.2 Reducible Nodes” and “4.3.5 Reduce Method” sections. Basically, this method is intended for people implementing or porting their dynamic langauges to .NET. So that they can create their own nodes that can “reduce” to standard … Read more

How do I set a field value in an C# Expression tree?

.Net 4.0 : now that there’s Expression.Assign, this is easy to do: FieldInfo field = typeof(T).GetField(“fieldName”); ParameterExpression targetExp = Expression.Parameter(typeof(T), “target”); ParameterExpression valueExp = Expression.Parameter(typeof(string), “value”); // Expression.Property can be used here as well MemberExpression fieldExp = Expression.Field(targetExp, field); BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp); var setter = Expression.Lambda<Action<T, string>> (assignExp, targetExp, valueExp).Compile(); setter(subject, “new value”); … Read more

How do I create an expression tree calling IEnumerable.Any(…)?

There are several things wrong with how you’re going about it. You’re mixing abstraction levels. The T parameter to GetAnyExpression<T> could be different to the type parameter used to instantiate propertyExp.Type. The T type parameter is one step closer in the abstraction stack to compile time – unless you’re calling GetAnyExpression<T> via reflection, it will … Read more

Error in C#: “an expression tree may not contain a base access” – why not?

Looking at the System.Linq.Expressions.Expression documentation, I don’t think there’s an expression type which represents “base member access”. Don’t forget that even though in your case it meant the same as just this, in other cases it wouldn’t: class Test { void Foo() { Expression<Func<string>> baseString = () => base.ToString(); } public override string ToString() { … Read more

Unable to cast object of type ‘System.Linq.Expressions.UnaryExpression’ to type ‘System.Linq.Expressions.MemberExpression’

You need a separate line to extract the Member where the input expression is a Unary Expression. Just converted this from VB.Net, so might be slightly off – let me know if I need to make any minor tweaks: public string GetCorrectPropertyName<T>(Expression<Func<T, Object>> expression) { if (expression.Body is MemberExpression) { return ((MemberExpression)expression.Body).Member.Name; } else { … Read more