很多if和else条件重复代码

时间:2018-08-09 23:00:15

标签: c#

我有一个场景,我根据选中的复选框进行过滤,现在我只有2个复选框,我需要将所有场景都覆盖到if中,否则条件如下:

//List Example:
 var projectTechnicians = (from DataRow dr in dtEmployeGuid.Rows
                                      where dr["Title"].ToString().Contains("Project Technician")
                                      select new
                                      {
                                          EmpGuid = (Guid)dr["EmpGuid"]
                                      }).ToList();




if (!chkProjectTechs.Checked && !chkTeamLeader.Checked)
{
    foreach (DataRowView list in lstTech.SelectedItems)
    {
        var selectedEmpGuid = (Guid)list[0];
        EmpGuid.Add(selectedEmpGuid);
    }
    parameters = ToDataTable(EmpGuid);
}
else if (!chkTeamLeader.Checked && chkProjectTechs.Checked)
{
    foreach (var technician in projectTechnicians)
    {
        EmpGuid.Add(technician.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid);
}
else if (!chkProjectTechs.Checked && chkTeamLeader.Checked)
{
    foreach (var teamLeader in teamLeaders)
    {
        EmpGuid.Add(teamLeader.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid);
}
else if (chkProjectTechs.Checked && chkTeamLeader.Checked)
{
    foreach (var technician in projectTechnicians)
    {
        EmpGuid.Add(technician.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid);

    foreach (var teamLeader in teamLeaders)
    {
        EmpGuid.Add(teamLeader.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid);
}

但是我需要添加更多复选框,但是我将foreach复选框添加到表单中,需要将其添加到每个条件中,最后一天,我将得到很长的代码。还有另一种方法吗?

1 个答案:

答案 0 :(得分:0)

您上一次"1.txt"的状况有问题。 else if被团队领导empGuids覆盖

parameters

您可以通过仅使用if条件来简化代码,请检查代码中的注释。

foreach (var technician in projectTechnicians)
    {
        EmpGuid.Add(technician.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid);

    foreach (var teamLeader in teamLeaders)
    {
        EmpGuid.Add(teamLeader.EmpGuid);
    }
    parameters = ToDataTable(EmpGuid); // Overwriting projectTechnicians added above.

编辑 如果使用的是LINQ,则可以使用下面的LINQ查询添加EmpGuid,而不是使用// add EmpGuids from lstTech if no check box is selected. // you need to add all checkboxes not selected in the condition if (!chkProjectTechs.Checked && !chkTeamLeader.Checked) { foreach (DataRowView list in lstTech.SelectedItems) { var selectedEmpGuid = (Guid)list[0]; EmpGuid.Add(selectedEmpGuid); } } // if projectTechnicians is checked, then add projectTechnicians EmpGuids to parameters if (chkProjectTechs.Checked) { foreach (var technician in projectTechnicians) { EmpGuid.Add(technician.EmpGuid); } } // add team leader Empguids if checked. if (chkTeamLeader.Checked) { foreach (var teamLeader in teamLeaders) { EmpGuid.Add(teamLeader.EmpGuid); } } // Add new checkbox conditions here // // perform your next operation on parameters here. // At this point you will have either lstTech employees or employees based on checkbox selection in EmpGuid list. parameters = ToDataTable(EmpGuid);

foreach