I have the following function: -
public IEnumerable<Employee> getEmployees(string department, string searchterm)
{
IEnumerable<Employee> query;
if (department == null || department == ""){
query = from e in db.Employees where e.Date_Leave == null orderby e.EmpSurname select e;
}else{
query = from e in db.Employees where (e.Date_Leave == null) && (e.EmpDept==department) orderby e.EmpSurname select e;
}
return query;
}
At the moment it's just looks at the 'department' variable to determine which query to run but I also want it to look at the 'searchTerm' variable which I will use against the 'EmpSurname' column My question is, is it possible to have just one query that will use 'department' and 'searchTerm' if they are not null and disregard them if they are null. It could also be that one is null and the other is not. Thank you
You can use:
var query = from e in db.Employees
where e.Date_Leave == null &&
(department == null || e.EmpDept == department) &&
(searchTerm == null || /* something using searchTerm */)
orderby e.EmpSurname
select e;
Or just conditionally add the queries as Marcin showed. Either approach should be fine.
See more on this question at Stackoverflow