How to build Expression<Func<T,bool>> from Expression<Func<T>>

.net, c#, linq, linq-expressions

Solution

Like this:

static Expression<Func<T,bool>> Munge<T>(Expression<Func<T>> selector)
{
    var memberInit = selector.Body as MemberInitExpression;
    if (memberInit == null)
        throw new InvalidOperationException("MemberInitExpression is expected");
    var p = Expression.Parameter(typeof(T), "x");

    Expression body = null;
    foreach (MemberAssignment binding in memberInit.Bindings)
    {
        var comparer = Expression.Equal(
            Expression.MakeMemberAccess(p, binding.Member),
            binding.Expression);
        body = body == null ? comparer : Expression.AndAlso(body, comparer);
    }
    if (body == null) body = Expression.Constant(true);

    return Expression.Lambda<Func<T, bool>>(body, p);
}

Problem

Is there a way to build `Expression<Func<T,bool>>` from `Expression<Func<T>>`? For example for class ``` public class MyClass { public int Prop1{get;set;} public int Prop2{get;set;} public int Prop3{get;set;} } ``` if `Expression<Func<T>>` is `() => new MyClass{Prop2 = 5}` then result should be `x => x.Prop2 == 5` if `Expression<Func<T>>` is `() => new MyClass{Prop1 = 1, Prop3 = 3}` then result should be `x => x.Prop1 == 1 && x.Prop3 == 3` In other words is it possible to create func with any number of conditions at runtime?

Original source