1

I have in my project one genericRepository with function like this:

public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null)
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

and this works fine in cases if I want to get elements filtered by only one object. What in the case I need to chain 3-4 where clauses? Is there any way to pass array of expressions if now what is the best way to make this thing work?

After reading your answers and comments I managed to make write this:

Expression<Func<Role, bool>> first = s => s.Id == 1;
Expression<Func<Role, bool>> second = s => s.RoleName != "null";
Expression<Func<Role, bool>> combined = Expression.Lambda<Func<Role, bool>>(Expression.And(first.Body, second.Body));

but this gives me

Additional information: Incorrect number of parameters supplied for lambda declaration

szpic
  • 4,346
  • 15
  • 54
  • 85
  • http://stackoverflow.com/questions/1131869/how-to-merge-two-c-sharp-lamba-expressions-without-an-invoke – Jevgenij Nekrasov Feb 14 '14 at 13:52
  • http://stackoverflow.com/questions/5047561/how-to-pass-an-array-of-orderby-expression-to-a-method – Ehsan Feb 14 '14 at 14:08
  • I fail to see how this method is actually making anything easier for you. Why not just take your queryable and call `Where`/`OrderBy`/etc. on it directly? – Servy Feb 14 '14 at 14:25
  • Idea was that to make one function which will fit all views with filtering i use instead of coding x methods which are 90% same – szpic Feb 14 '14 at 14:29

2 Answers2

1

I would advise you to use LinqKit to build the expression from where you are calling this method.

Here's an example:

  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }

  var products = productRepository.Get(predicate)
Moeri
  • 9,104
  • 5
  • 43
  • 56
0

Probably you can combine your predicates

Combining Predicates

Jevgenij Nekrasov
  • 2,690
  • 3
  • 30
  • 51
  • Please note that link-only answers are useless when the link breaks. Please always add a summary that highlights the points of interest to the OP. – Gert Arnold Feb 14 '14 at 15:50