是否可以用一系列嵌套的.Where
语句来做if
?
这就是我想要做的:
public class Repository {
public async Task<IQueryable<Order>> orders (int? accountId, int? userId) {
IQueryable<Order> orders;
orders = _context.Orders
.Where(o =>
{
int filterCount = 0;
int filterCriteriaMet = 0;
// if the accountId param is not null
// increment the filter counter
// and check if this order's accountId == param
// if so, increment filterCriteriaMet counter
if (accountId != null)
{
filterCount++;
if (o.AccountId == accountId)
{
filterCriteriaMet++;
}
}
// if the userId param is not null
// increment the filter counter
// and check if this order's userId == param
// if so, increment filterCriteriaMet counter
if (userId != null)
{
filterCount++;
if (o.UserId == userId) {
filterCriteriaMet++;
}
}
return filterCount == filterCriteriaMet;
});
return orders;
}
}
但这给了我以下错误:
带有语句主体的lambda表达式无法转换为表达式树
答案 0 :(得分:5)
当然!
.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));