The question arose how to implement search in applications. Suppose we have 5 parameters by which it is possible to search for employees: The period of time to get a job (beginning of period, end of period); Name; Surname; Middle name. You can search for any of the parameters (as soon as by name [everything else is ignored], and in full name, and for all parameters taken together). An object of type comes to the service:
public class SearchContext { public DateTime? BeginDate { get; set; } public DateTime? EndDate { get; set; } public string Name { get; set; } public string SecondName { get; set; } public string MiddleName { get; set; } } How to correctly search the table for these parameters? As an option, you can pile up ifov type:
public IEnumerable<Employee> Search(SearchContext searchContext) { if (string.IsNullOrEmpty(searchContext.Name) && string.IsNullOrEmpty(searchContext.SecondName) && string.IsNullOrEmpty(searchContext.MiddleName) && searchContext.BeginDate.HasValue && searchContext.EndDate.HasValue) return _employeeDAO.GetEmployeesByPeriod(searchContext.BeginDate.Value, searchContext.EndDate); //.....продолжаем проверять разные условия } The second option is to create some special class of type ExpressionBuilder, then the code will look something like this:
public IEnumerable<Employee> Search(SearchContext searchContext) { var builder = new ExpressionBuilder<Employee>(); if (!string.IsNullOrEmpty(searchContext.Name)) builder = builder.Property(x => x.Name).AreEquals(searchContext.Name); if (!string.IsNullOrEmpty(searchContext.SecondName)) builder = builder.Property(x => x.SecondName).AreEquals(searchContext.SecondName); var condition = builder.Build(); return _employeeDAO.GetEmployeesByQuery(condition); } The second option seems to be more successful as the readability of the method improves. I want to hear the opinion of knowledgeable people.