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

时间:2021-05-20

复制代码 代码如下:
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;

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章