Click here to Skip to main content
15,897,273 members
Articles / Programming Languages / C#
Tip/Trick

Expression Tree

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
8 Nov 2012CPOL3 min read 33.2K   13   3
Expression Tree

What is Expression Tree ?

Expression is not like other code, but it like binary tree data structure where each node is representing an object children(s). Expression tree is get derived from the Lambda Expression which you can see easily once you can drill down in framework class. One good reason of Expression tree is it allows to create dynamic linq queries.

Expression Class

using System.Collections.ObjectModel;
 
namespace System.Linq.Expressions
{
    // Summary:
    //     Represents a strongly typed lambda expression as a data structure in the
    //     form of an expression tree. This class cannot be inherited.
    //
    // Type parameters:
    //   TDelegate:
    //     The type of the delegate that the System.Linq.Expressions.Expression<tdelegate>
    //     represents.
    public sealed class Expression<tdelegate> : LambdaExpression
    {
        // Summary:
        //     Compiles the lambda expression described by the expression tree into executable
        //     code.
        //
        // Returns:
        //     A delegate of type TDelegate that represents the lambda expression described
        //     by the System.Linq.Expressions.Expression<tdelegate>.
        public TDelegate Compile();
    }
}
</tdelegate></tdelegate></tdelegate>

Syntax of Expression  


Expression<Func<type,returnType>> = (param) => lamdaexpresion;
NameSpace System.Linq.Expressions;
 

contains defincation of Expression Tree class. so you need to include this namespace before using the Expression in your code.

Example

Expression<Func<int,int, int>> lambda = (a,b) => a *  b;
 
Expression Tree for the above expression
 

 
Install Expression Tree visualizer

If you are not having visualizer to view expression tree than you can install it by following below instruction
Download Samples : http://code.msdn.microsoft.com/csharpsamples
Compile code : Official_Visual_Studio_2008_C#_Samples\ExpressionTreeVisualizer\C#\ExpressionTreeVisualizer\
Get Dll from:
bin\Debug\expressionTreeVisualizer.dll
Install Dll on path : C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers
 
 

Expression Tree Parts

Expression tree is consistence of following part, each part is shown in blow images.

Body


 
Parameters

 
NodeType and Type Of Expression

 
Difference Between Lamdab Expression and Expression

In above example I assigned lambda expression to Expression type, by doing that way enviroment represent lambda expression as expression tree not as lambda expression. And if you see memory represtation of expression tee its a object represention of expression which is already seen in expression tree visualizer, which is differnt than lambda epxssion IL.
when you write

Func<int,int, int> lambdaExpression = (a,b) => a *  b;
its a lambda expression.
 
Important point to Note here is
You cannot use lambda expressions with a statement to create an expression tree
Expression<Func<int, int, bool>> IsAGreater =
    (a, b) => { if (a > b)  return true; else return false; };

above code throw compile time error.
 

How to Create Expression Tree ?

Fist Way:
First way is very easy that I already sawn is above discussion "Create Lambda expression and assign it to expression."
 

Expression<Func<int,int, int>> lambda = (a,b) => a *  b;

Something as above.
 
 

Second Way:
To create expression you need to follow the below steps one by one. I am also going to show the functions that can be used in dynamic expression.
 

private void CreateExpressionTree()
 {
Create parameter for the expression.
ParameterExpression exp1 = Expression.Parameter(typeof(int), "a");
        ParameterExpression exp2 = Expression.Parameter(typeof(int), "b");
Create body of the expression, over here in this example using multiply function to get the multiplication of the two parameter.
BinaryExpression exp = Expression.Multiply(exp1,exp2);
        var lamExp = Expression.Lambda<Func<int, int, int>>                     
               (exp, new ParameterExpression[] { exp1, exp2 });
Compile method compile the expression tree and Invoke allows to execute the compiled expression tree. As you see you need to pass the values for the parameter of expression tree.
int c = (lamExp.Compile()).Invoke(2,5); 
        Response.Write(c); 
}

 
Application of Expression Tree ?

One Application I fond for the Expression tree is to make use of expression to build the dynamic linq query.
 

Example 1 : - Bind query to get data and sort the data dynamically. As you see in below code I build query and sorting data by passing name of the property in people object. In example Email property used to sort which can be replace by Name property.
 

private void BindAndSort()
    {
        List<people> people = new List<people>
            {
                new People(){ Name = "Pranay",Email="pranay@test.com",CityID=2 },
                new People(){ Name = "Heamng",Email="Hemang@test.com",CityID=1 },
                new People(){ Name = "Hiral" ,Email="Hiral@test.com",CityID=2},
                new People(){ Name = "Maitri",Email="Maitri@test.com",CityID=1 }
            };
 
        ParameterExpression param = Expression.Parameter(typeof(People), "People");
 
        Expression ex = Expression.Property(param, "Email");
 
        var sort= Expression.Lambda<Func<People, object>>(ex, param); 
 
        var sortedData =
                        (from s in people
                         select s).OrderBy<people, object>(sort.Compile()).ToList<people>();
        GridViewNotional.DataSource = sortedData;
        GridViewNotional.DataBind();
    }
Example 2 : - Build query to search data from the people entity using Email property and Email starts with "h". Over here property can be replace with the Name property.
ParameterExpression param = Expression.Parameter(typeof(People), "People");
Expression ex = Expression.Property(param, "Email");
 
// Get the method information for the String.StartsWith() method   
MethodInfo mi = typeof(String).
                GetMethod("StartsWith", new Type[] { typeof(String) });
MethodCallExpression startsWith = 
                Expression.Call(ex, mi, Expression.Constant("h"));
 
Expression<Func<People, bool>> expression =     
            Expression.Lambda<Func<People, bool>>(startsWith, param);
 
var searchData = (from s in people
             select s).Where(expression.Compile()).ToList<people>();        
</people>
Both the Example 1 and Example 2 methods can be replace with the generics. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
Generalgeneral Pin
Member 1359720427-Dec-17 20:34
Member 1359720427-Dec-17 20:34 
GeneralComments Pin
Andrew Rissing9-Nov-12 4:05
Andrew Rissing9-Nov-12 4:05 
Questiondebugger Pin
pip0109-Nov-12 3:37
pip0109-Nov-12 3:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.