Manually constructing Expressions

9 01 2008

[ Please read Marlon’s blog post before reading my post 😉 ]

My friend Marlon posted about how to parse Expression given a Lambda expression something like,

x=>x.Name==”Marlon”

But what if you want to construct the above Lambda expression manually 🙂

Yes, that is 100% possible! You can build your queries manually too 😀

Looking again at the query,

x=>x.Name==”Marlon”

We can split into two parts

1) x

2) x.Name==”Marlon”

What do these mean?

1) x is the parameter and is of type Customer

2) The property Name is checked against the string Marlon which is nothing but the property Name’s value

To speak in “LINQ” language,

1) x is a ParameterExpression of type Customer

2) x.Name==”Marlon” is a MemberExpression whose,

a) left expression is the property Name, and

b) right expression is the ConstantExpression of value “Marlon”

There is nothing new here. if you look at how Marlon has parsed the tree, we could easily arrive to the above query construction technique

So, having understood the basics, now let us construct it 🙂

//construct the parameter which is x and it is of type Customer
ParameterExpression xParam = Expression.Parameter(typeof(Customer), "x");

//construct our MemberExpression whose
//left expression is x.Name, and
//right expression its value "Marlon"
MemberExpression leftExpr = MemberExpression.Property(xParam, "Name");
Expression rightExpr = Expression.Constant(customer.Name);

//construct our BinaryExpression which is x.Name=="Marlon"
BinaryExpression myExpr = MemberExpression.Equal(leftExpr, rightExpr);

//now build our Expression using the parameter and BinaryExpression
//x=>x.Name=="Marlon"
Expression<Func<Customer, bool>> lambdaExpr =
    Expression.Lambda<Func<Customer, bool>>
        (
            myExpr,
            new ParameterExpression[] { xParam }
        );

//call our function and pass our expression which we constructed
customer_url = GetCustsomerUrl(lambdaExpr);

//display the returned value
Console.WriteLine("URL = {0}", customer_url);

Its nothing but parsing the expression tree in reverse 😀

You can download the sample here

Advertisements