By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,683 Members | 1,597 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Building an Expression Tree for the given Lambda Expression

100+
P: 293
Here is the Code Sample for converting the Given LINQ Expression to currosponding Expression Tree.

Expand|Select|Wrap|Line Numbers
  1. //using LINQAlias = System.Linq.Expressions;
  2.  
  3.  List<Host> dinnerList = new List<Host>() 
  4.         { 
  5.             new Host 
  6.             { 
  7.                 DinnerID = 4, HostName = "Abc", HostContactDetails = "123456789", 
  8.                 Dinner = new Dinner() { DinnerID = 4, Discription = "Description1", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, DateTime.Now.Day - 3) } 
  9.             }, 
  10.             new Host 
  11.             { 
  12.                 DinnerID = 1, HostName = "Xyz", HostContactDetails = "987654321", 
  13.                 Dinner = new Dinner() { DinnerID = 1, Discription = "Description2", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 2, DateTime.Now.Day - 1) } 
  14.             }, 
  15.             new Host 
  16.             { 
  17.                 DinnerID = 1, HostName = "Abc", HostContactDetails = "7845915356", 
  18.                 Dinner = new Dinner() { DinnerID = 1, Discription = "Description3", Eventdate = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, DateTime.Now.Day - 2) } 
  19.             }, 
  20.             new Host 
  21.             { 
  22.                 DinnerID = 1, HostName = "Pqr", HostContactDetails = "9475815364", Dinner = new Dinner() { DinnerID = 1, Discription = "Description4", Eventdate = DateTime.Now } 
  23.             } 
  24.         };
// 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.Where(host => host.DinnerID == 1 && host.Dinner.Eventdate <= DateTime.Now).OrderBy(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.

Expand|Select|Wrap|Line Numbers
  1. IQueryable<Host> HostList = dinnerList.AsQueryable<Host>();
  2.  
  3.                 //Step 1 : Declare the parameter 'host'
  4.                 // So, Build the parameter expression for 'host' as
  5.  
  6.                 LINQAlias.ParameterExpression hostParameterExpression = Expression.Parameter(typeof(Host), "host");
  7.  
  8.                 // Step 2 : Use this Parameter to build the expression for the  host.DinnerID == 1
  9.                 // L.H.S expression is the properety of the object Host hence need to build the expression as
  10.  
  11.                 Expression left = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("DinnerID", typeof(int)));
  12.                 Expression right = Expression.Constant(1);
  13.  
  14.                 Expression predicateExpression = Expression.Equal(left, right);
  15.  
  16.                 //Step 3 : Build an expression for host.Dinner.Eventdate <= DateTime.Now
  17.  
  18.                 Expression anotherLeft = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("Dinner", typeof(Dinner)));
  19.                 Type typeDinner = anotherLeft.Type;
  20.                 Expression eventDateofDinner = Expression.Property(anotherLeft, typeDinner.GetProperty("Eventdate", typeof(DateTime)));
  21.  
  22.                 Expression anotherRight = Expression.Constant(DateTime.Now);
  23.  
  24.                 Expression anotherPredicateExpression = Expression.LessThanOrEqual(eventDateofDinner, anotherRight);
  25.  
  26.                 //Step 4: Build a tree for host => host.DinnerID == 1 && host.Dinner.Eventdate <= DateTime.Now from the subExpressions predicateExpression and anotherPredicateExpression
  27.  
  28.                 Expression predicateBody = Expression.AndAlso(predicateExpression, anotherPredicateExpression);
  29.  
  30.                 //Step 5 :Call Where on the Queryable DataSource by passing this expression to the call
  31.                 // Expression Tree for dinnerList3.Where(host => host.DinnerID == 3 && host.Dinner.Eventdate <= DateTime.Now)
  32.  
  33.                 MethodCallExpression whereCallExpression = Expression.Call(
  34.                      typeof(Queryable),
  35.                      "Where",
  36.                       new Type[] { HostList.ElementType},
  37.                       HostList.Expression,
  38.                      Expression.Lambda<Func<Host, bool>>(predicateBody, new ParameterExpression[] { hostParameterExpression }));
  39.  
  40.  
  41.                 //Step 6:Build the expression for host.HostName
  42.  
  43.                 Expression hostNamePredicateBody = Expression.Property(hostParameterExpression, typeof(Host).GetProperty("HostName", typeof(string)));
  44.  
  45.                 //Step 7: Extend the tree for the call to order by
  46.                 //.OrderBy(host => host.HostName)
  47.  
  48.                 MethodCallExpression orderByExpression = Expression.Call(
  49.                    typeof(Queryable),
  50.                    "OrderBy",
  51.                    new Type[] { HostList.ElementType, typeof(string) }, // type of in arguments to the OrderBy queryable Method
  52.                    whereCallExpression,
  53.                    Expression.Lambda<Func<Host, string>>(hostNamePredicateBody, new ParameterExpression[] { hostParameterExpression })
  54.  
  55.                    // 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                   
  56.                    to get built is whereexpression.OrderBy(host => host.name).In the expression host is the in argument to the method and                     
  57.                    string is the out argument.So the container expression implies the same . It creates the dynamic method with the                         
  58.                    return Type and signature as "<<ruturnType>> Func(<<inArgument>>) --> string func(host)".
  59.  
  60.                     // An immediate next argument to the method is the body of the method which is host.HostName represented by an expression                    
  61.                     hostNamePredicateBody and an argument hostParameterExpression tends to the Host which is an in-argumnet to the Func Method.
  62.  
  63.                    );
  64.  
  65.  
  66.                 // Step 9 :Create an executable Query
  67.  
  68.                  IQueryable<Host> result  = HostList.Provider.CreateQuery<Host>(orderByExpression);
  69.  
  70.                 //Step 10 : Execute the Query and Display the result.
  71.                 foreach (Host host in result)
  72.                     MessageBox.Show(host.HostName);
Jun 4 '12 #1
Share this Article
Share on Google+