Unwieldy LINQ statement with multiple search criteria

c#, linq

Solution

What about something like this:

IQueryable<Employee> employees = DB.Employees;

if (!string.IsNullOrEmpty(FirstName))
{
    employees = employees 
        .Where(emp => emp.FirstName.Contains(fName));
}
if (!string.IsNullOrEmpty(LastName))
{
    employees = employees 
        .Where(emp => emp.Last.Contains(lName));
}

Problem

I have a form with multiple search criteria that a user can use to search for employee data, e.g. FirstName, LastName, HireDate, Department, etc. I am using LINQ and am wondering what method could I use to query a collection of Employes given any of of the search criteria, i.e. a user does not have to enter all, but they do have to enter at least one of the search parameters. So far, while testing my LINQ statement with two search parameters in place, it seems that I have to see if the search parameter is entered or not. If this is the case, then this can get quite unwieldy for many search parameters. ``` // only FirstName is entered if (!string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName)) { var employees = DB.Employees .Where(emp => emp.FirstName.Contains(fName)); } // only LastName is entered else if (string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName)) { var employees = DB.Employees .Where(emp => emp.LastName.Contains(lName)); } // both parameters are entered else if (!string.IsNullOrEmpty(FirstName) && !string.IsNullOrEmpty(LastName)) { var employees = DB.Employees .Where(emp => emp.FirstName.Contains(fName)) .Where(emp => emp.LastName.Contains(lName)); } ``` FYI, I initially thought that I could just append Where() statements to my LINQ statement with the pertinent search parameters but I noticed that not all records were being returned that should and thus the above logic of if-then statements.

Original source