清洁If语句的代码

时间:2017-08-08 07:53:14

标签: scala if-statement logic

我有这样的声明,我该如何优化这个逻辑。我想大约1个小时,但我找不到。

我怎样才能简化这种逻辑?

if (model.WaitingChecked) 
{
    if (model.selectedStatus != 0) 
    {
        model.DataList = data.Where(x => x.status != 6 && x.status == model.selectedStatus);
        return View(model);
    }

    model.DataList = data.Where(x => x.status != 6);
    return View(model);
}

if (model.SelectedStatus != 0) 
{
    model.DataList = data.Cast<DataDetailedList>().Where(x => x.status == model.selectedStatus);
    return View(model);
}

1 个答案:

答案 0 :(得分:2)

您可以在不同条件下使用模式匹配。请记住,模式匹配需要详尽无遗。意味着需要定义值的每个组合。

(model.WaitingChecked, model.selectedStatus ) match{
  case (true, 0) =>
    model.DataList = data.Where(x => x.status != 6)
    View(model)
  case (true, _) =>
    model.DataList = data.Where(x => x.status != 6 && x.status == model.selectedStatus)
    View(model)
  case (_, 0) =>
    //missing logic for model.selectedStatus is zero return
  case (_, _) =>
    model.DataList = data.Cast<DataDetailedList>().Where(x => x.status == model.selectedStatus)
    View(model)
}