使用外部表达式参数的成员属性来调用C#内部表达式

5
我正在使用Albahari的PredicateBuilder,可以在这里找到http://www.albahari.com/nutshell/predicatebuilder.aspx,它能够过滤Linq-to-SQL应用程序中的结果,效果非常好。
现在我想要做的是,重复使用现有的过滤谓词表达式来过滤一个具有现有过滤对象作为属性的对象。
例如,我有两个类:Order和Customer。 我已经有了一个方法,返回一个Expression<Func<Customer, bool>>,该方法是使用上述谓词生成器构建的。 现在我想将此方法重复使用在我的Order过滤方法中,该方法将通过某种方式将Order.Customer属性(表达式?)传递到我的Customer过滤方法中,并返回一个Expression<Func<Customer, bool>>
我大致有以下内容(远没有完成,但我希望您能理解我的意思):
public class CustomerSearchCriteria
{
    public Expression<Func<Customer, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Customer>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Name))
        {
            result = result.And(c => SqlMethods.Like(c.Name, this.Name));
        }

        // etc. etc. etc

} 


public class OrderSearchCriteria
{
    public Expression<Func<Order, bool>> FilterPredicate()
    {
        // Start with predicate to include everything
        var result = PredicateBuilder.True<Order>();

        // Build predicate from criteria
        if (!String.IsNullOrEmpty(this.Reference))
        {
            result = result.And(o => SqlMethods.Like(o.Reference, this.Reference));
        }

        // etc. etc. etc
        // This is where I would like to do something like:
        // result = result.And(o => o.Customer "matches" this.CustomerCriteria.FilterPredicate()
} 

有没有Linq表达式大牛能帮忙?

提前感谢。

1个回答

3
如果您使用Albaharis的LinqKit,您应该能够像这样做:
var customerFilter = this.CustomerCriteria.FilterPredicate();
// create an expression that shows us invoking the filter on o.Customer
Expression<Func<Order, bool>> customerOrderFilter = 
    o => customerFilter.Invoke(o.Customer);
// "Expand" the expression: this creates a new expression tree
// where the "Invoke" is replaced by the actual predicate.
result = result.And(customerOrderFilter.Expand())

非常感谢。这正是我所需要的。我一直在使用PredicateBuilder,但没有包含或查看LinqKit的其余部分。 - Darren

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