Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public IQueryable<T> Search<T>(IQueryable<T> query, params Expression<Func<T, object>>[] memberSelectors)
- {
- if (PhraseGroups.Count() == 0)
- return query;
- var phrasesParamExpression = Expression.Parameter(typeof(List<string>), "phrases");
- var phraseParamExpression = Expression.Parameter(typeof(string), "phrase");
- var entityParamExpression = Expression.Parameter(typeof(T), "entity");
- var memberSelectorParamExpression = Expression.Parameter(typeof(Expression<Func<T, object>>), "memberSelector");
- var condition = Expression.AndAlso(
- Expression.Equal(Expression.Invoke(memberSelectorParamExpression, entityParamExpression), Expression.Constant(null)),
- Expression.Call( Expression.Call(Expression.Invoke(memberSelectorParamExpression, entityParamExpression), typeof(object).GetMethod("ToString")) , typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), phraseParamExpression)
- );
- var memberSelectorsExpression = Expression.Lambda<Func<Expression<Func<T, object>>, bool>>(condition, memberSelectorParamExpression);
- // this IEnumerable<TSource> source, Func<TSource, bool> predicate
- var anyMethod = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
- .First(m => m.Name == "Any" && m.GetParameters().Count() == 2);
- var phraseCondition = Expression.Lambda<Func<string, bool>>(Expression.Call(null, anyMethod.MakeGenericMethod(typeof(Expression<Func<T, object>>)), Expression.Constant(memberSelectors), memberSelectorsExpression), phraseParamExpression);
- var phrasesAnyExpr = Expression.Lambda<Func<List<string>, bool>>(Expression.Call(null, typeof(Enumerable).GetMethod("All").MakeGenericMethod(typeof(string)), phrasesParamExpression, phraseCondition), phrasesParamExpression);
- var whereCondition = Expression.Lambda<Func<T, bool>>(Expression.Call(null, anyMethod.MakeGenericMethod(typeof(List<string>)), Expression.Constant(PhraseGroups), phrasesAnyExpr), entityParamExpression);
- return query.Where(whereCondition);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement