entity framework: conditional filter

Viewed 11019

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:All, teenager, adult, senior

if I had to build an SQL string for this filter, it would be something like this:

if (Country != "All") sql += "country = " + Country
if (Income != "All") sql += "and income = " + Income
if (Age != "All") sql += "and age = " + Age;

So, basically, the user can filter by some, but not necessary all fields.

How do you do this using Entity Framework ?

Thanks !

3 Answers

You can use extension method to help readable and maintainable code.

  • LinqExtensions.cs
public static class LinqExtensions
{
    public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
    {
        return condition ? source.Where(predicate) : source;
    }
}
  • Refactoring code
List<Person> peoples = context.People
    .WhereIf(Country != "All", p => p.Country == Country)
    .WhereIf(Income != "All", p => p.Income == Income)
    .WhereIf(Age != "All", p => p.Age == Age)
    .ToList();
Related