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;}
public List<Task> Tasks {get; set;}
public DateTime FindTaskStartDate(Task task)
{}
}
How should i perform a recursive search (linq perhaps) to find the task with the earliest start date?
My initial approach involved too many for loops and it ended becoming a bit of a mess and quickly spiraling out of control. Here’s my second attempt:
public DateTime FindTaskStartDate(Task task)
{
DateTime startDate = task.Start;
if(task.HasSubTasks())
{
foreach (var t in task.Tasks)
{
if (t.Start < startDate)
{
startDate = t.Start;
if (t.HasSubTasks())
{
//What next?
//FindTaskStartDate(t);
}
}
}
}
return startDate;
}
Any nicer solutions out there to solve this problem?
Thanks
You’re right, recursion is the right approach here. Something like this should work:
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<Task>that returns all the tasks in the tree. Finding the smallest start date would then be as easy as: