entity framework: conditional filter

前端 未结 2 1306
难免孤独
难免孤独 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:57

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

    IQueryable 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 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.

提交回复
热议问题