I have a form with several search criteria that the user can use to search for employee data, for example. FirstName, LastName, HireDate, Department, etc.
I use LINQ and wonder what method I can use to query the Employes collection based on any of the search criteria, that is, the user does not need to enter everything, but they need to enter at least one of the search parameters.
So far, checking my LINQ statement with two search parameters, it seems like I should check if the search parameter is entered or not. If so, then this can become rather cumbersome for many search options.
// 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 add Where () statements to my LINQ statement with the appropriate search parameters, but noticed that not all records were returned, which should and therefore the above logic of if-then statements.
source share