Let\'s say I have Customers table and I want to filter it by the following:
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.
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.