I have this extension method:
public static IQueryable<T> FilterByEmployee<T>(this IQueryable<T> source, EmployeeFilter filter) where T : class, IFilterableByEmployee { if (!string.IsNullOrEmpty(filter.Gender)) source = source.Where(e => e.Employee.Gender == filter.Gender); if (!string.IsNullOrEmpty(filter.NationalityID)) source = source.Where(e => e.Employee.NationalityID == filter.NationalityID); // filter the group if (filter.IncludeChildGroups) { var groups = Security.GetAllChildGroups(filter.GroupID); source = source.Where(e => e.Employee.EmployeeGroupID.HasValue && groups.Contains(e.Employee.EmployeeGroupID.Value)); } else { source = source.Where(e => e.Employee.EmployeeGroupID == filter.GroupID); } // filter status if (filter.OnlyActiveEmployees) source = source.Where(e => e.Employee.Status == "Active"); return source; }
and another that is exactly the same, but it directly filters the Employees context:
public static IQueryable<T> Filter<T>(this IQueryable<T> source, EmployeeFilter filter) where T : Employee { if (!string.IsNullOrEmpty(filter.Gender)) source = source.Where(e => e.Gender == filter.Gender); if (!string.IsNullOrEmpty(filter.NationalityID)) source = source.Where(e => e.NationalityID == filter.NationalityID); // filter the group if (filter.IncludeChildGroups) { var groups = Security.GetAllChildGroups(filter.GroupID); source = source.Where(e => e.EmployeeGroupID.HasValue && groups.Contains(e.EmployeeGroupID.Value)); } else { source = source.Where(e => e.EmployeeGroupID == filter.GroupID); } // filter status if (filter.OnlyActiveEmployees) source = source.Where(e => e.Status == "Active"); return source; }
I hate the idea of โโhaving almost the same code twice, how can I combine these two methods into one? (if possible) or at least do it in two ways, but filtering in one of them? the source code is much longer, which is also one of the reasons.
source share