【问题标题】:linq-to-sql combine expressionslinq-to-sql 组合表达式
【发布时间】:2011-02-17 01:36:41
【问题描述】:

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

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]'."}

【问题讨论】:

    标签: linq-to-sql lambda


    【解决方案1】:

    试试这个它的构建器,这样你就必须为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);
    }
    

    【讨论】:

    • 感谢您的回复。你知道为什么会出现这个异常吗?
    • 上述异常? “二进制...”?它是由答案或问题中的阻塞引起的吗?
    • 在问题中 - 在上面那一行
    • 唯一的问题是在行中返回 (Expression.Lambda>(Expression.AndAlso(first.Body, toInvoke), first.Parameters));看起来编译器无法解析“T”。如果我用具体类型替换“T”,一切正常。
    • 你试过改变 Combine -> Combine 吗?可能是我的帖子中的错字(我刚刚更新了它)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多