简体   繁体   中英

C# Entity Framework Linq: Select Where If/Else

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

当然!

.Where(o => AccountId != null && o.AccountId == accountId || (UserId != null && o.UserId == UserId));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM