Click here to Skip to main content
13,148,573 members (52,954 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


11 bookmarked
Posted 8 Nov 2012

Expression Tree

, 8 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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();

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.


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 :
Compile code : Official_Visual_Studio_2008_C#_Samples\ExpressionTreeVisualizer\C#\ExpressionTreeVisualizer\
Get Dll from:
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.



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); 

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="",CityID=2 },
                new People(){ Name = "Heamng",Email="",CityID=1 },
                new People(){ Name = "Hiral" ,Email="",CityID=2},
                new People(){ Name = "Maitri",Email="",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;
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>();        
Both the Example 1 and Example 2 methods can be replace with the generics. 


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


About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

Hey, I am Pranay Rana, working as a ITA in 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 -
My CV :-


You may also be interested in...

Comments and Discussions

GeneralComments Pin
Andrew Rissing9-Nov-12 4:05
memberAndrew Rissing9-Nov-12 4:05 
Questiondebugger Pin
pip0109-Nov-12 3:37
memberpip0109-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170924.2 | Last Updated 9 Nov 2012
Article Copyright 2012 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid