为给定的Lambda表达式构建表达式树

构建LINQ表达式树
本文详细介绍如何将LINQ查询转换为表达式树,通过实例演示了如何使用表达式树来构建复杂的查询条件,包括筛选和排序操作。

这是用于将给定的LINQ表达式转换为对应的表达式树的代码示例。

//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 } 
            } 
        };
//语句:对于给定的数据源,如果我们要查找主持了DinnerID 1的主机,

//对应的Lambda表达式为

// DinnerList.Where(host => host.DinnerID == 1 && host.Dinner.Eventdate <= DateTime.Now).OrderBy(host => host.HostName);

//这是创建此Lambda表达式的表达式树的逐步说明

//将集合转换为Queryable对象,以便调用IQueryable扩展方法。

//作为方法“ Where”和“ orderBy”仅可在Qeryable对象上调用。

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

From: https://bytes.com/topic/net/insights/940724-building-expression-tree-given-lambda-expression

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值