当前位置: 移动技术网 > IT编程>开发语言>c# > c#反射表达式树模糊搜索示例

c#反射表达式树模糊搜索示例

2019年07月18日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:public static expression<func<t, bool>> getsearchexpression<t

复制代码 代码如下:

public static expression<func<t, bool>> getsearchexpression<t>(string searchstring)
        {
            expression<func<t, bool>> filter = null;

            if (string.isnullorempty(searchstring)) return null;
            var left = expression.parameter(typeof(t), "m");

            expression expression = expression.constant(false);
            t obj = default(t);
            var type = typeof(t);
            obj = (t)activator.createinstance(type);
           var propertyinfos = type.getproperties();

            foreach (var propertyinfo in propertyinfos)
            {

                if (propertyinfo.name.tolower() == "id" || propertyinfo.propertytype == typeof(datetime)) continue;
                expression tostring = expression.call
         (
            expression.property(left, typeof(t).getproperty(propertyinfo.name).name),

           typeof(object).getmethod("tostring", new type[] { })

         );
                expression right = expression.call

                      (

                          tostring,

                        typeof(string).getmethod("contains", new type[] { typeof(string) }),

                        expression.constant(searchstring)

                      );
                expression = expression.or(right, expression);
            }

            filter = expression.lambda<func<t, bool>>(expression, new[] { left });

            return filter;

        }

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网