Reputation: 1694
Is it possible to do a .Where
with a series of nested if
statements?
Here's what I'd like to do:
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;
}
}
but this gives me the following error:
A lambda expression with a statement body cannot be converted to an expression tree
Upvotes: 2
Views: 2685
Reputation: 1035
Sure!
.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));
Upvotes: 5