Reputation: 6095
I have for example a Task class which can report how long a task would take to complete. This class however can contain subtasks of the same type.
public class Task
{
public string Name{get; set;}
public DateTime Start {get; set;}
public DateTime Finish {get; set;}
public List<Task> SubTasks {get; set;}
public TimeSpan GetDuration()
{
return Finish - Start;
}
public TimeSpan GetTotalDuration()
{
//How?
}
}
SubTasks can be several levels deep, there's no logical limit right now. I'm not sure how to design the method responsible for walking the subtasks and accumulate the TimeSpan value?
Any elegant ideas appreciated?
Thanks
Upvotes: 1
Views: 152
Reputation: 14660
I'd just do:
public TimeSpan GetTotalDuration()
{
if (SubTasks != null)
return GetDuration() + SubTasks.Sum(t => t.GetTotalDuration());
return GetDuration();
}
Using Linq.
Edit: To handle the case where SubTasks is null (via Kristof's answer).
Upvotes: 8
Reputation: 3315
public TimeSpan GetTotalDuration()
{
var duration = GetDuration();
if(SubTasks != null && SubTasks.Count > 0)
{
foreach (var t in SubTasks)
{
duration += t.GetTotalDuration();
}
}
return duration;
}
Upvotes: 2