根据其他变量列表更新变量

Updating a variable based on a list of other variables

这更像是一个逻辑问题,而不是实施问题。

class Step {    
  public string StepStatus {get ; set;}

  public List<Task> Tasks {get ; set;}

  public Step() {

    Tasks= new List<Task>() ;
  }

  //on some event I call this method that updates StepStatus based on status of
  //all task statuses

  private void UpdateStepStatusFromTasks() {
    foreach (Task t in Tasks) {
            // t.TaskStatus
            // set StepStatus here  
            // LOGIC here

    }
  }
}

每个任务对象 t 都有自己的 TaskStatus 字符串。

  1. 如果所有任务状态都是 "DONE" ,将步骤状态设置为 "DONE"

  2. 如果所有任务状态都是 "TODO" ,将步骤状态设置为 "TODO"

  3. 如果任务状态之一是 "DOING" ,将步骤状态设置为 "DOING"

  4. 如果任务状态之一是 "DONE" 和一个是 "TODO" ,将步骤状态设置为 "DOING"

实现这个的最佳方法是什么?在代码复杂度和更少的笨拙性方面。

我是怎么解决的:

 private void UpdateStepStatusFromTasks()
        {



            if ( Tasks.All(t => t.TaskStatus.Equals("Not Started")))
                StepStatus = "Not Started";
            else if (Tasks.All(t => t.TaskStatus.Equals("Completed")))
                StepStatus = "Completed";
            else
                StepStatus = "In Progress";




        }

正如 Blorgbeard 所指出的,这是所有人的完美用例。一个例子:

tasks.All( (t) => t.Status == Done);

t.Status == Done 只是一个例子,它可以是任何布尔表达式。

你可以这样做:

var taskStatuses = Tasks.Select(t => t.TaskStatus).Distinct().ToList();
if (taskStatuses.Count == 1) {
    // all tasks are the same status, so that's the step status
    return taskStatuses[0];
}
if (taskStatuses.Contains("DOING")) return "DOING";
if (taskStatuses.Contains("DONE") && taskStatuses.Contains("TODO")) {
    return "DOING";
}
// whatever other logic you want
foreach(var step in steps)
{
    step.StepStatus =
        step.Tasks.All(x => x.Status == "DONE") ? "DONE" :
        step.Tasks.All(x => x.Status == "TODO") ? "TODO" :
        step.Tasks.Any(x => x.Status == "DOING") ? "DOING" :
        step.Tasks.Any(x => x.Status == "DONE ") && step.Tasks.Any(x => x.Status == "TODO") ? "DOING"
        : "UNKNOWN_STATUS";
}