欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-31 12:12:28
复制代码 代码如下:public static expression> getsearchexpression

复制代码 代码如下:

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;

        }