entity framework: conditional filter

前端 未结 2 1299
难免孤独
难免孤独 2020-12-09 06:12

Let\'s say I have Customers table and I want to filter it by the following:

  • Country: All, US, UK, Canada
  • Income: All, low, high, medium
  • Age:A
2条回答
  •  攒了一身酷
    2020-12-09 06:38

    You can include conditional parameter this way:

    return Customers.Where(
                    customer =>
                    customer.Name == Name &&
                    (Age == "All" || customer.Age == Age) &&
                    (Income == "All" || customer.Income == Income) &&
                    (Country == "All" || customer.Country == Country)
                    ).ToList();
    

    If some condition is true (e.g. country is equal to All), then all parameter condition becomes true, and this parameter does not filter result.

提交回复
热议问题