·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> C# 反射 表达式树 模糊搜索

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

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

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;}