szpic
szpic

Reputation: 4496

Passing multiple lambda expression to the function

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

Upvotes: 1

Views: 851

Answers (2)

Moeri
Moeri

Reputation: 9294

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)

Upvotes: 1

Jevgenij Nekrasov
Jevgenij Nekrasov

Reputation: 2760

Probably you can combine your predicates

Combining Predicates

Upvotes: 0

Related Questions