如何执行递归搜索? [英] How to perform a recursive search?
问题描述
我有一个Task类,可以包含相同类型的子任务
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)
{}
}
我应该如何执行递归搜索(也许可能是linq)以找到最早开始日期的任务?
How should i perform a recursive search (linq perhaps) to find the task with the earliest start date?
我最初的方法涉及太多的for循环,最终变得一团糟,并迅速失控.这是我的第二次尝试:
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?
谢谢
推荐答案
您是对的,在这里递归是正确的方法.这样的事情应该起作用:
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;
}
我删除了task.HasSubTasks()
的支票,因为这只会使代码更加复杂,而没有任何额外的好处.
I removed the check for task.HasSubTasks()
, because it only makes the code more complicated without any added benefit.
如果您发现经常编写的代码需要遍历树中的所有任务,则可能需要使其更通用.例如,您可能有一个返回IEnumerable<Task>
的方法,该方法返回树中的所有任务.这样,找到最小的开始日期就很容易了:
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:
IterateSubTasks(task).Min(t => t.Start)
这篇关于如何执行递归搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!