linq-to-sql结合表达式

Vic*_*tor 2 lambda linq-to-sql

有什么方法可以将表达式列表合并为一个吗?我有List<Expression<Child, bool>> expList并尝试合并为一个(AndAlso)并得到

Expression<Child, bool> combined = Combine(expList);
Run Code Online (Sandbox Code Playgroud)

组合表达的预期用法是:

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

我正在尝试这样的事情:

var result = expList.Cast<Expression>().
Aggregate((p1, p2) => Expression.AndAlso(p1, p2));
Run Code Online (Sandbox Code Playgroud)

但得到一个例外

{"The binary operator AndAlso is not defined for the types 'System.Func`2[Child,System.Boolean]' and 'System.Func`2[Child,System.Boolean]'."}
Run Code Online (Sandbox Code Playgroud)

Nix*_*Nix 5

尝试将其作为构建器,因此您必须以递归方式为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);
}
Run Code Online (Sandbox Code Playgroud)