Building an Expression Tree for the given Lambda Expression

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madankarmukta
    Contributor
    • Apr 2008
    • 308

    Building an Expression Tree for the given Lambda Expression

    Here is the Code Sample for converting the Given LINQ Expression to currosponding Expression Tree.

    Code:
    //using LINQAlias = System.Linq.Expressions;
     
     List<Host> dinnerList = new List<Host>() 
            { 
                new Host 
                { 
                    DinnerID = 4, HostName = "Abc", HostContactDetails = "123456789", 
                    Dinner = new Dinner() { DinnerID = 4, Discription = "Description1", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, DateTime.Now.Day - 3) } 
                }, 
                new Host 
                { 
                    DinnerID = 1, HostName = "Xyz", HostContactDetails = "987654321", 
                    Dinner = new Dinner() { DinnerID = 1, Discription = "Description2", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 2, DateTime.Now.Day - 1) } 
                }, 
                new Host 
                { 
                    DinnerID = 1, HostName = "Abc", HostContactDetails = "7845915356", 
                    Dinner = new Dinner() { DinnerID = 1, Discription = "Description3", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, DateTime.Now.Day - 2) } 
                }, 
                new Host 
                { 
                    DinnerID = 1, HostName = "Pqr", HostContactDetails = "9475815364", Dinner = new Dinner() { DinnerID = 1, Discription = "Description4", Eventdate = DateTime.Now } 
                } 
            };
    // Statement :For the Given DataSource if We want to find out the Hosts who had hosted the dinnerID 1.
    // Corresponding Lambda expression would be
    // dinnerList.Wher e(host => host.DinnerID == 1 && host.Dinner.Eve ntdate <= DateTime.Now).O rderBy(host => host.HostName);

    // Here is the step wise ellaboration for creating the Expression Tree of this Lambda expression

    // Convert the collection to the Queryable Object so as to make a call to the IQueryable Extension Method.
    // As The Method "Where" and "orderBy" are callable only on Qeryable object.

    Code:
    IQueryable<Host> HostList = dinnerList.AsQueryable<Host>();
    
    				//Step 1 : Declare the parameter 'host'
    				// So, Build the parameter expression for 'host' as
    
    				LINQAlias.ParameterExpression hostParameterExpression = Expression.Parameter(typeof(Host), "host");
    
    				// Step 2 : Use this Parameter to build the expression for the  host.DinnerID == 1
    				// L.H.S expression is the properety of the object Host hence need to build the expression as
    
    				Expression left = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("DinnerID", typeof(int)));
    				Expression right = Expression.Constant(1);
    
    				Expression predicateExpression = Expression.Equal(left, right);
                
    				//Step 3 : Build an expression for host.Dinner.Eventdate <= DateTime.Now
                
    				Expression anotherLeft = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("Dinner", typeof(Dinner)));
    				Type typeDinner = anotherLeft.Type;
    				Expression eventDateofDinner = Expression.Property(anotherLeft, typeDinner.GetProperty("Eventdate", typeof(DateTime)));
    
    				Expression anotherRight = Expression.Constant(DateTime.Now);
    
    				Expression anotherPredicateExpression = Expression.LessThanOrEqual(eventDateofDinner, anotherRight);
    
    				//Step 4: Build a tree for host => host.DinnerID == 1 && host.Dinner.Eventdate <= DateTime.Now from the subExpressions predicateExpression and anotherPredicateExpression
    
    				Expression predicateBody = Expression.AndAlso(predicateExpression, anotherPredicateExpression);
    
    				//Step 5 :Call Where on the Queryable DataSource by passing this expression to the call
    				// Expression Tree for dinnerList3.Where(host => host.DinnerID == 3 && host.Dinner.Eventdate <= DateTime.Now)
    
    				MethodCallExpression whereCallExpression = Expression.Call(
    					 typeof(Queryable),
    					 "Where",
    					  new Type[] { HostList.ElementType},
    					  HostList.Expression,
    					 Expression.Lambda<Func<Host, bool>>(predicateBody, new ParameterExpression[] { hostParameterExpression }));
    
               
    				//Step 6:Build the expression for host.HostName
    
    				Expression hostNamePredicateBody = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("HostName", typeof(string)));
    
    				//Step 7: Extend the tree for the call to order by
    				//.OrderBy(host => host.HostName)
    
    				MethodCallExpression orderByExpression = Expression.Call(
    				   typeof(Queryable),
    				   "OrderBy",
    				   new Type[] { HostList.ElementType, typeof(string) }, // type of in arguments to the OrderBy queryable Method
    				   whereCallExpression,
    				   Expression.Lambda<Func<Host, string>>(hostNamePredicateBody, new ParameterExpression[] { hostParameterExpression })
                   
    				   // Last Parameter to the Call represents the container Lambda expression that holds the expression builtin the call. For e.g. here the final expression going                   
    				   to get built is whereexpression.OrderBy(host => host.name).In the expression host is the in argument to the method and                     
    				   string is the out argument.So the container expression implies the same . It creates the dynamic method with the                         
    				   return Type and signature as "<<ruturnType>> Func(<<inArgument>>) --> string func(host)".
    			   
    					// An immediate next argument to the method is the body of the method which is host.HostName represented by an expression                    
    					hostNamePredicateBody and an argument hostParameterExpression tends to the Host which is an in-argumnet to the Func Method.
    
    				   );
    
    
    				// Step 9 :Create an executable Query
                
    				 IQueryable<Host> result  = HostList.Provider.CreateQuery<Host>(orderByExpression);
    
    				//Step 10 : Execute the Query and Display the result.
    				foreach (Host host in result)
    					MessageBox.Show(host.HostName);
Working...