I'm writing a query where, based on what input the user has provided, I need to add "disjunctive" conditions (that is to say "or" conditions). To do this with "conjunctive" conditions ("and" conditions"), this is fairly straight forward...
var employees = repository.GetAll<Employee>(); // returns IQueryable
if (!string.IsNullOrEmpty(firstName))
employees = employees.Where(e => e.FirstName.Contains(firstName));
if (!string.IsNullOrEmpty(lastName))
employees = employees.Where(e => e.LastName.Contains(lastName));
if (!string.IsNullOrEmpty(email))
employees = employees.Where(e => e.Email.Contains(email));
The resulting query will have 0 to 3 AND conditions depending on whether firstName, lastName, or email are populated. But is there a way to do this using OR conditions? For example, is there something like the following...
// Notice these use of OrWhere which does not exist...
var employees = repository.GetAll<Employee>(); // returns IQueryable
if (!string.IsNullOrEmpty(firstName))
employees = employees.OrWhere(e => e.FirstName.Contains(firstName));
if (!string.IsNullOrEmpty(lastName))
employees = employees.Orwhere(e => e.LastName.Contains(lastName));
if (!string.IsNullOrEmpty(email))
employees = employees.OrWhere(e => e.Email.Contains(email));
I know that I can make a very large where condition...
var employees = repository.GetAll<Employee>().Where(e =>
(!string.IsNullOrEmpty(firstName) && e.FirstName.Contains(firstName)) ||
(!string.IsNullOrEmpty(lastName) && e.LastName.Contains(lastName)) ||
(!string.IsNullOrEmpty(email) && e.Email.Contains(email))
);
...but the query produced is not efficient and the code does not seem as elegant to me. I'm hoping there's a better way to do this that looks more like the 2nd example.