How to perform a recursive search?

前端 未结 3 795
无人及你
无人及你 2020-12-24 11:03

I have a Task class which can have sub tasks of the same type

public class Task
{
  public DateTime Start { get; set;}
  public DateTime Finish { get; set;}
         


        
3条回答
  •  悲哀的现实
    2020-12-24 11:42

    You're right, recursion is the right approach here. Something like this should work:

    public DateTime FindTaskStartDate(Task task)
    {
        DateTime startDate = task.Start;
    
        foreach (var t in task.Tasks)
        {
            var subTaskDate = FindTaskStartDate(t);
            if (subTaskDate < startDate)
                startDate = subTaskDate;
        }
    
        return startDate;
    }
    

    I removed the check for task.HasSubTasks(), because it only makes the code more complicated without any added benefit.

    If you find your often write code that needs to walk all of the tasks in the tree, you might want to make this more general. For example, you could have a method that returns IEnumerable that returns all the tasks in the tree. Finding the smallest start date would then be as easy as:

    IterateSubTasks(task).Min(t => t.Start)
    

提交回复
热议问题