c#反射表达式树模糊搜索示例_C#教程-查字典教程网
c#反射表达式树模糊搜索示例
c#反射表达式树模糊搜索示例
发布时间:2016-12-28 来源:查字典编辑
摘要:复制代码代码如下:publicstaticExpressionGetSearchExpression(stringSearchString)...

复制代码 代码如下:

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#教程学习
    热门C#教程学习
    编程开发子分类