加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 05:42:05 所属栏目:百科 来源:网络整理
导读:复制代码 代码如下: public static ExpressionFuncT,bool GetSearchExpressionT(string SearchString) { ExpressionFuncT,bool filter = null; if (string.IsNullOrEmpty(SearchString)) return null; var left = Expression.Parameter(typeof(T),"m"); Expr

复制代码 代码如下:

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;

        }

您可能感兴趣的文章:

  • c# GridControl的模糊查询实现代码
  • C#对图片进行马赛克处理可控制模糊程度的实现代码

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读