我需要按字符串字段名称构建搜索。
例如这段代码:
SearchProvider.Search(records, "First", "S2");
应该等于:
SearchProvider.Search(records, x => x.First, "S2");
问题:将字符串转换为Linq lambda表达式。
我怎么能这样做?
答案 0 :(得分:2)
您应该使用Expression.Lambda
将字符串转换为lambda表达式,例如:
public IQueryable<TModel> Search<TModel>(IQueryable<TModel> model, string selector, string searchFor)
{
var param = Expression.Parameter(typeof(TModel), "x");
var contains = Expression.Call(
Expression.PropertyOrField(param, selector),
"Contains", null, Expression.Constant(searchFor)
);
var predicate = Expression.Lambda<Func<TModel, bool>>(contains, param);
model = model.Where(predicate);
return model;
}
接下来,对于公平搜索,您应该做两件事:
以下是示例:
public IQueryable<TModel> Search<TModel>(IQueryable<TModel> model, string selector, object searchFor)
{
var param = Expression.Parameter(typeof(TModel), "x");
var tostring = Expression.Call(
Expression.PropertyOrField(param, selector),
"ToString", null, null
);
var tolower = Expression.Call(
tostring,
"ToLower", null, null
);
var contains = Expression.Call(
tolower,
"Contains", null, Expression.Constant(searchFor)
);
var predicate = Expression.Lambda<Func<TModel, bool>>(contains, param);
model = model.Where(predicate);
return model;
}
祝你好运。