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