zoukankan      html  css  js  c++  java
  • 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;
            }

  • 相关阅读:
    k8s资源编排
    虫师『软件测试』基础 与 测试杂谈
    虫师『性能测试』文章大汇总
    OMCS ——卓尔不群的网络语音视频聊天框架(跨平台)
    ESFramework ——成熟的C#网络通信框架(跨平台)
    2022.2 区块链的技术架构
    pytest文档80 内置 fixtures 之 cache 写入中文显示\u4e2d\u6587问题(用打补丁方式解决) 上海
    翻译校正
    Inside WCF Runtime
    Web Services Security
  • 原文地址:https://www.cnblogs.com/swarb/p/9924210.html
Copyright © 2011-2022 走看看