LINQ to SQL 合并表达式

3

有没有办法将表达式列表合并成一个? 我有一个 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个回答

6
尝试使用这个生成器,因此您需要对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);
}

谢谢回复。你知道为什么会出现这个异常吗? - Victor
上面的异常是什么?“二进制……”?这是由答案中的块还是问题中的块引起的? - Nix
唯一的问题是在这行代码 return (Expression.Lambda<Func<T, Boolean>>(Expression.AndAlso(first.Body, toInvoke), first.Parameters)); 中,编译器似乎无法解析“T”。如果我用具体类型替换“T”,那么它就可以正常工作了。 - Victor
你试过将 Combine 改为 Combine<T> 吗?可能是我帖子中的笔误(我刚刚更新了它)。 - Nix
仍然可以使用list.Aggregate调用此方法;不必使用foreach。 - dudeNumber4
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接