代码重构以提高性能
我有一个从数据库中获取的所有部门的清单 现在,我想根据某些条件从部门列表中获取所有合格部门
下面是将为每个部门循环的代码,并使用转换案例检查条件是否匹配,然后将该部门添加到符合条件的部门列表中
List<EligibleDepartments> eligibleDepartments = new List<EligibleDepartments>();
//use the following boolean values for eliminating common logic execution again and again
bool IsCriteriaForABCDMatchSet = false;
bool IsCriteriaForEFMatchSet = false;
foreach (var department in departmentTypes) // here departmentTypes is the list of departments fetched from database
{
switch (department.DepartmentTypeId)
{
// here DepartmentTypes is the enum
case (int)DepartmentTypes.DepartmentA:
case (int)DepartmentTypes.DepartmentB:
case (int)DepartmentTypes.DepartmentC:
case (int)DepartmentTypes.DepartmentD:
if (IsCriteriaForABCDMatchSet || IsCriteriaForABCDMatches(students))
{
eligibleDepartments.Add(department);
IsCriteriaForABCDMatchSet = true;
}
break;
case (int)DepartmentTypes.DepartmentE:
case (int)DepartmentTypes.DepartmentF:
if (IsCriteriaForEFMatchesSet || IsCriteriaForEFMatches(students))
{
eligibleDepartments.Add(department);
IsCriteriaForEFMatchSet = true;
}
break;
case (int)DepartmentTypes.DepartmentG:
if (IsCriteriaForGMatches(students))
{
eligibleDepartments.Add(department);
}
break;
case (int)DepartmentTypes.DepartmentH:
if (IsCriteriaForIMatches(students))
{
eligibleDepartments.Add(department);
}
break;
case (int)DepartmentTypes.DepartmentI:
if (IsCriteriaForIMatches(students))
{
eligibleDepartments.Add(department);
}
break;
case (int)DepartmentTypes.DepartmentJ:
if (IsCriteriaForJMatches(students))
{
eligibleDepartments.Add(department);
}
break;
case (int)DepartmentTypes.DepartmentK:
if (IsCriteriaForKMatches(students))
{
eligibleDepartments.Add(department);
}
break;
}
}
但是以某种方式我觉得这段代码会降低性能。 有什么替代的方法来重构此代码,并避免在此处使用切换用例。 任何帮助,将不胜感激。