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开发者_如何学Python>().
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]'."}
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);
}
精彩评论