1. 程式人生 > >expression select表示式動態構建

expression select表示式動態構建

參考:

http://blog.csdn.net/tastelife/article/details/7340205

http://blog.csdn.net/sweety820/article/details/39203087

原始碼:

        private static Expression<Func<TSource, TResult>> CreateSelecter<TSource, TResult>(Dictionary<string,string> fieldDic)
        {
            Expression<Func<TSource, TResult>> selector = null;


            //(rec)
            ParameterExpression param = Expression.Parameter(typeof(TSource), "x");
            //new ParadigmSearchListData 
            var v0 = Expression.New(typeof(TResult));
            //Number
            List<MemberBinding> bindingList = new List<MemberBinding>();
            foreach (var item in fieldDic)
            {
                var p = typeof(TResult).GetProperty(item.Key);
                Expression right = GetProperty<TSource>(null, item.Value, param);
                //right= Expression.Constant(right, p.PropertyType);
                var v = Expression.Convert(GetProperty<TSource>(null, item.Value, param), p.PropertyType);
                var m = Expression.Bind(p, v);
                bindingList.Add(m);
            }
            Expression body = Expression.MemberInit(v0, bindingList);


          selector = (Expression<Func<TSource, TResult>>)Expression.Lambda(body, param);


            return selector;
        }


        public static Expression GetProperty<T>(Expression source, string Name, ParameterExpression Param)
        {
            Name = Name.Replace(")", "");
            string[] propertys = null;
            if (Name.Contains("=>"))
            {
                propertys = Name.Split('.').Skip(1).ToArray();
            }
            else
            {
                propertys = Name.Split('.');
            }
            if (source == null)
            {
                source = Expression.Property(Param, typeof(T).GetProperty(propertys.First()));
            }
            else
            {
                source = Expression.Property(source, propertys.First());
            }
            foreach (var item in propertys.Skip(1))
            {
                source = GetProperty<T>(source, item, Param);
            }
            return source;
        }