0
目前,我有一个可用的帮助函数,它创建一个简单的表达式来搜索一个通用实体(TEntity)以获得搜索项(单个词/短语)。它创建下面的表达式:C#动态表达式树使用Where(或Any)和泛型
q => q.Product.ProductTitle.Contains(searchText: 'red shirt')
我只需要扩展该助手来搜索每个字包括在搜索项(例如SEARCHTEXT:“红色衬衫” - > searchTerms:[“红”,“衬衫” ])
var searchTerms = searchText.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
searchTerms.Any(s => !q.Product.ProductTitle.ToLower().Contains(s))
函数列在下面 - 我已经评论了需要完成的代码。
public static Expression<Func<TEntity, bool>> CreateSearchQuery(List<PropertyInfo> searchPropertiesList, string searchText, SearchType searchType = SearchType.Contains)
{
if(string.IsNullOrWhiteSpace(searchText) || searchPropertiesList == null || searchPropertiesList.Count <= 0)
{
return null;
}
var searchTerms = searchText.ToLower().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var searchExpressionList = new List<Expression<Func<TEntity, bool>>>();
foreach(var property in searchPropertiesList.Where(x => x.GetCustomAttributes(false).Any(c => c.GetType() != typeof(NotMappedAttribute))))
{
//search param
var searchParam = Expression.Parameter(typeof(string), "s");
//search type
var searchTypeMethod = typeof(string).GetMethod(searchType.ToString(), new[] { typeof(string) });
//entity expression.
var entityParam = Expression.Parameter(typeof(TEntity), "q");
var entityProperty = Expression.Property(entityParam, property);
var entityExpression = Expression.Call(
Expression.Call(entityProperty, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes)),
searchTypeMethod,
Expression.Call(searchParam, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes))
);
var entityPredicateBody = Expression.Lambda<Func<TEntity, bool>>(entityExpression, entityParam);
////TODO: CONSIDER EACH TERM AND CREATE WHERE/ANY EXPRESSION
//searchTerms.Any(s => !q.Product.ProductTitle.ToLower().Contains(s))
//var filterExpression = Expression.Call(
// typeof(Enumerable),
// "Where",
// new[] { typeof(TEntity) },
// searchParam,
// entityPredicateBody);
//var expressionBody = Expression.Lambda<Func<TEntity, bool>>(filterExpression, searchParam);
//TODO: REPLACE WITH NEW EXPRESSION (expressionBody)
searchExpressionList.Add(entityPredicateBody);
}
为什么你有用单引号(''红衬衫')包裹的字符串?如果你想能够扩展它来接受多个字符串,你可以使用它作为你的函数参数:'(List searchPropertiesList,SearchType searchType,params string [] args)',那么你只需要处理传入的1个(或更多)'args'。请参阅:https://msdn.microsoft.com/en-us/library/w5zay9db.aspx –
感谢您的反馈Zac。我会在未来更新或改变行为。 –