linq-to-sql结合表达式

时间:2010-03-31 14:34:16

标签: linq-to-sql lambda

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

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

组合表达的预期用法是:

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

我正在尝试这样的事情:

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

但是获得例外

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

1 个答案:

答案 0 :(得分: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);
}