Ace McCloud
Ace McCloud

Reputation: 900

Updating a variable based on a list of other variables

This is more of a logic question than implementation.

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

    }
  }
}

Each Task object t has its own TaskStatus string.

  1. if All Task Statuses are "DONE" , set Step Status to "DONE"

  2. if All Task Statuses are "TODO" , set Step Status to "TODO"

  3. if one of the Task Statuses are "DOING" , set Step Status to "DOING"

  4. if one of the Task Statuses are "DONE" and one is "TODO" , set Step Status to "DOING"

What is the best way to implement this? In terms of code complexity and less kludgyness.

How I solved it :

 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";




        }

Upvotes: 0

Views: 61

Answers (3)

akekir
akekir

Reputation: 523

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";
}

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103467

You could do something like this:

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

Upvotes: 0

Domysee
Domysee

Reputation: 12846

As Blorgbeard pointed out, this is the perfect use case for all and any. An example:

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

t.Status == Done is just an example, it can be any boolean expression.

Upvotes: 0

Related Questions