Victor
Victor

Reputation: 297

linq-to-sql combine expressions

Is there any way I can combine list of expressions into one? I have List<Expression<Child, bool>> expList and trying to combine into one (AndAlso) and get

Expression<Child, bool> combined = Combine(expList);

Intended usage for combined expression is this:

//type of linqFilter is IQueryable<Parent>
linqFilter = linqFilter.SelectMany(p => p.Child).
         Where(combined).Select(t=> t.Parent); 

I am trying something like this:

var result = expList.Cast<Expression>().
Aggregate((p1, p2) => Expression.AndAlso(p1, p2));

But getting an exception

{"The binary operator AndAlso is not defined for the types 'System.Func`2[Child,System.Boolean]' and 'System.Func`2[Child,System.Boolean]'."}

Upvotes: 3

Views: 1780

Answers (1)

Nix
Nix

Reputation: 58522

Try this its a builder so you would have to recursively call it for each in expList

public Expression<Func<T, bool>> Combine<T>(Expression<Func<T, Boolean>> first, Expression<Func<T, Boolean>> second)
{
   var toInvoke = Expression.Invoke(second, first.Parameters);

   return (Expression<Func<T, Boolean>>)Expression.Lambda(Expression.AndAlso(first.Body, toInvoke), first.Parameters);
}

Upvotes: 6

Related Questions