您的位置:首页 > 编程语言 > C#

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

2018-10-12 14:07 639 查看


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;

        }

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: