首页 > 学院 > 开发设计 > 正文

C# 反射 表达式树 模糊搜索

2019-11-15 02:31:28
字体:
来源:转载
供稿:网友

C# 反射 表达式树 模糊搜索

反射实体T,非datetime字段反射获取表达式树

publicstaticExPRession<Func<T,bool>>GetSearchExpression<T>(stringSearchString){Expression<Func<T,bool>>filter=null;if(string.IsNullOrEmpty(SearchString))returnnull;varleft=Expression.Parameter(typeof(T),"m");Expressionexpression=Expression.Constant(false);Tobj=default(T);vartype=typeof(T);obj=(T)Activator.CreateInstance(type);varpropertyInfos=type.GetProperties();foreach(varpropertyInfoinpropertyInfos){if(propertyInfo.Name.ToLower()=="id"||propertyInfo.PropertyType==typeof(DateTime))continue;Expressiontostring=Expression.Call(Expression.Property(left,typeof(T).GetProperty(propertyInfo.Name).Name),typeof(object).GetMethod("ToString",newType[]{}));Expressionright=Expression.Call(tostring,typeof(string).GetMethod("Contains",newType[]{typeof(string)}),Expression.Constant(SearchString));expression=Expression.Or(right,expression);}filter=Expression.Lambda<Func<T,bool>>(expression,new[]{left});returnfilter;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表