如何向现有的 lambda 表达式添加条件?

How to add a condition to existing lambda expression?

考虑以下 class:

public class Customer
{
    public int Id {get; set;}
    public int GroupId {get; set;}
    public int Number {get; set;}
    public string Name {get; set;}
}

我在服务层有一个方法:

public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}

调用代码为:

var customer = customerService.Get(x => x.Number == number);

在上面的方法中,用户根据 属性(不包括 GroupId,因为它隐藏在 ViewModel 中)搜索客户。然而,用户总是被分配到一个组,因此,他只能在他的组内搜索客户。所以GroupId必须动态添加。

如何将 GroupId 添加到上述方法中的 where 表达式。 GroupId 可能已在表达式中可用,也可能不可用。

使用 PredicateBuilder 您可以帮助构建可以添加到调用中的表达式。这将允许您执行如下操作。

public void DoSearch(MyViewModel vm)
{
    Expression<Func<Customer, bool>> myFilter = x => yourCurrentFilterLogic;
    var combined = myFilter.And(x => x.GroupId == vm.GroupId);   //PredicateBuilder extension method
    var customers = Get(combined);
}

public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}