entity framework: conditional filter

前端 未结 2 1298
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2020-12-09 06:57

    LINQ to Entity queries return IQueryable's, so you can build your query this way:

    IQueryable<Person> query = context.People;
    
    if (Country != "All")
    {
        query = query.Where(p => p.Country == Country);
    }
    
    if (Income != "All")
    {
        query = query.Where(p => p.Income == Income);
    }
    
    if (Age != "All")
    {
        query = query.Where(p => p.Age == Age);
    }
    
    List<Person> fetchedPeople = query.ToList();
    

    This case is almost too simple, but this is very helpful in more complex situations when you need to add filtering dynamically.

    0 讨论(0)
提交回复
热议问题