How to Create a Multiple-Condition Lambda Expression Tree

c# expression-trees lambda linq


Note: I know it's much simple to create this using dynamic linq but I want to learn.

I want to create a lambda that "finds": Name=David AND Age=10.

 class Person
       public int Age { get; set; }
       public string Name { get; set; }

    var lambda = LabmdaExpression<Person>("Name", "David", "Age", 10);

static Expression<Func<T, bool>> LabmdaExpression<T>(string property1, string value1, string property2, int value2)

     ParameterExpression parameterExpression = Expression.Parameter(typeof(Person), "o");
     MemberExpression memberExpression1 = Expression.PropertyOrField(parameterExpression, property1);
     MemberExpression memberExpression2 = Expression.PropertyOrField(parameterExpression, property2);

     ConstantExpression valueExpression1 = Expression.Constant(value1, typeof(string));
     ConstantExpression valueExpression2 = Expression.Constant(value2, typeof(int));

     BinaryExpression binaryExpression1 = Expression.Equal(memberExpression1, valueExpression1);
     BinaryExpression binaryExpression2 = Expression.Equal(memberExpression2, valueExpression2);

     var ret1 =   Expression.Lambda<Func<T, bool>>(binaryExpression1, parameterExpression);
     var ret2 =   Expression.Lambda<Func<T, bool>>(binaryExpression2, parameterExpression);

6/9/2011 4:11:03 PM

Accepted Answer

Expression andExpression = Expression.AndAlso(binaryExpression1, binaryExpression2);

return Expression.Lambda<Func<T, bool>>(andExpression , parameterExpression);

Edit - comment

You just chain together all your expresions

so in order to get this expression X AND (Y OR (Z OR Q))

Expression ZorQ = Expression.OrElse(zExp, qExp);
Expression YorZorQ = Expression.OrElse(yExp, ZorQ);
Expression XandYorZorQ = Expression.AndAlso(xExp, YorZorQ);
6/9/2011 4:30:14 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow