Reputation: 1016
I have a couple of C# business class as follows:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string DepartmentCode { get; set; }
public string HireDate { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime Gender { get; set; }
}
public class EmployeeManagement
{
public List<Employee> GetEmployees(FilterExpression criteria)
{
throw new System.NotImplementedException();
}
}
The goal is to get the list of employees by passing various filter conditions e.g. all employees belonging to particular department, or hired after a particular date or all female employees or a combination of criterias (involving AND or OR conditions). I don't wish to implement many of the overloaded methods for each of the filter criteria since the end users are defining the filter criteria and i can not assume all possible cases.
Can you please help in designing the "FilterExpression" class that i can pass to GetEmployees method? Any other alternate approach suggestion would be welcome.
Thanks.
More details: The employee data is stored in a DB table. I don't want to bring in all the employees in List<Employee>
and then filter the data. My goal is to generate the SQL "where clause" from the filter expression so that from the database itself, I get the filtered Employee dataset. I am struggling with the class design of the FilterExpression class as asked above.
Upvotes: 2
Views: 2360
Reputation: 43523
You must tell us what kind of expression/filter you want to pass to the method. Otherwise I'll give a cheat answer:
public List<Employee> GetEmployees(Expression<Func<Employee,bool>> predicate)
{
return AllEmployees.Where(predicate.Compile()).ToList();
}
you can use:
var bob = GetEmployees(emp=>emp.Name.Equals("Bob")).FirstOrDefault;
var ITStaff = GetEmployees(emp=>emp.DepartmentCode.Equals("IT"));
Upvotes: 2
Reputation: 69252
Why not use an Expression<Func<Employee,bool>>
instead? Although it's typically associated with LINQ it doesn't have to be. You could pass a lambda and examine the expression tree at runtime that way.
var employees = GetEmployees(x => x.HireDate > DateTime.Today.AddDays(-7))
Upvotes: 0