Iva*_*ono 1 c# linq lambda expression
考虑以下类:
public class Customer
{
public int Id {get; set;}
public int GroupId {get; set;}
public int Number {get; set;}
public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
我在服务层有一个方法可以做到:
public Customer Get(Expression<Func<Customer, bool>> where)
{
return customerRepository.Get(where);
}
Run Code Online (Sandbox Code Playgroud)
调用代码为:
var customer = customerService.Get(x => x.Number == number);
Run Code Online (Sandbox Code Playgroud)
在上面的方法中,用户根据属性搜索客户(不包括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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6366 次 |
| 最近记录: |