We saw more about Lambda Expression in our Part 1 of this series .Wonder how those were compiled or how those expressions parsed?
To do so, we need to get into Expression Trees!
So what is an Expression Tree?
Expression trees are nothing but those which represent the query itself.
Let us take a simple example.
· The compiler constructs a delegate which takes an input parameter of type string and returns a value of type string
But, how about this
· The compiler generates an Expression Tree which we can parse and do something with the data
(This post gives a small introduction to Expression Trees. Expression Trees itself is a big topic but this post will help us go through some of the basics with a simple example)
Say we have a class called Student which has only one property – Name
And now we have a small function which is going to take an expression as its parameter and return the value for which the expression is queried for.
So, if we pass an expression,
We need to get back Chakkaradeep , as that’s what we queried. This isn’t a good example, but I would say its good to understand how Expressions are parsed J
Let me show you the function directly now,
That’s a bit confusing! Whats happening ?
Expression is being parsed 🙂
Yes, take our expression again,
Expressions always a Body property. In the above expression, we have a BinaryExpression
As you might have guessed by now, a BinaryExpression is something that has a binary operator
So lets take the Body and break it into two pieces
Now we have extracted our BinaryExpression body which has a Left property and Right property, as shown above in the diagram.
The Left property will hold n.Name
The Right Property will hold Chakkaradeep
And our Node Type or the Binary operator is == (Equality)
And that’s what we have done,
As now you have the values, you could do anything with them and parse them 🙂
But yes, it would be more complicated if we have multiple queries coming up, like,
n=>n.Name==”Chakkaradeep” && n.Name==”Chaks”
And our sample will not work for the above query as we havent dealt with it. I leave to the reader to explore more on how to recursively parse Expressions 🙂
What if we need to manually build Expressions?
You can 🙂
We just use the technique of how we parsed to build the expression manually.
First, we need to create a ParameterExpression of type Student and also tell that our paramter variable is x
And now we need to build our BinaryExpression whose Left Property is a MemberExpression which has the Property Name and the Right Property a value
All good now to build our Expression. Remember, we haven’t yet built our Expression, but we do have the bits and pieces that we need to build our expression
And now we build our Expression,
There you go! We build it telling that we have a ParameterExpression of type Student and the parameter is x which is associated with the BinaryExpression
And now you can directly pass this lambdaExpr to our function
You can download the sample here