Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. public IQueryable<T> Search<T>(IQueryable<T> query, params Expression<Func<T, object>>[] memberSelectors)
  2. {
  3. if (PhraseGroups.Count() == 0)
  4. return query;
  5.  
  6. var phrasesParamExpression = Expression.Parameter(typeof(List<string>), "phrases");
  7. var phraseParamExpression = Expression.Parameter(typeof(string), "phrase");
  8. var entityParamExpression = Expression.Parameter(typeof(T), "entity");
  9. var memberSelectorParamExpression = Expression.Parameter(typeof(Expression<Func<T, object>>), "memberSelector");
  10.  
  11. var condition = Expression.AndAlso(
  12. Expression.Equal(Expression.Invoke(memberSelectorParamExpression, entityParamExpression), Expression.Constant(null)),
  13. Expression.Call( Expression.Call(Expression.Invoke(memberSelectorParamExpression, entityParamExpression), typeof(object).GetMethod("ToString")) , typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), phraseParamExpression)
  14. );
  15.  
  16.  
  17. var memberSelectorsExpression = Expression.Lambda<Func<Expression<Func<T, object>>, bool>>(condition, memberSelectorParamExpression);
  18. // this IEnumerable<TSource> source, Func<TSource, bool> predicate
  19. var anyMethod = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
  20. .First(m => m.Name == "Any" && m.GetParameters().Count() == 2);
  21.  
  22. var phraseCondition = Expression.Lambda<Func<string, bool>>(Expression.Call(null, anyMethod.MakeGenericMethod(typeof(Expression<Func<T, object>>)), Expression.Constant(memberSelectors), memberSelectorsExpression), phraseParamExpression);
  23.  
  24. var phrasesAnyExpr = Expression.Lambda<Func<List<string>, bool>>(Expression.Call(null, typeof(Enumerable).GetMethod("All").MakeGenericMethod(typeof(string)), phrasesParamExpression, phraseCondition), phrasesParamExpression);
  25.  
  26. var whereCondition = Expression.Lambda<Func<T, bool>>(Expression.Call(null, anyMethod.MakeGenericMethod(typeof(List<string>)), Expression.Constant(PhraseGroups), phrasesAnyExpr), entityParamExpression);
  27.  
  28. return query.Where(whereCondition);
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement