Reputation: 77
I have a big broblem.
I have a TaskGroup object. Each TaskGroup has: a 'Task' object and a List < TaskGroup > . (has a list of objects of itself in it). It is supposed to be a tree.
Having a 'TaskGroup' object that has 'List ' in it. I need to get the single largest Date value from the 'Task' object in each object in the 'TaskGroup' list.
public class TaskGroup
{
public ProjectTask Task { get; set;}
public List<TaskGroup> ChildTask { get; set; } = new List<TaskGroup>();
}
public class Task
{
public int Id { get; set;}
public DateTime Date { get; set; }
}
In the diagram - having "my object" I have to get the largest date marked in red.
Does anyone know how to do this? Thanks
Upvotes: 1
Views: 55
Reputation: 37020
To get the largest date from the immediate children, you can just use a simple Linq statement:
var maxDate = taskGroup.ChildTask.Max(c => c.Task.Date);
To get the max date from all taskGroups under the main taskGroup, you can recursively check all the children for their max date:
static DateTime GetMaxDate(TaskGroup group)
{
if (group == null) return DateTime.MinValue;
var maxDate = group.Task?.Date ?? DateTime.MinValue;
foreach (var child in group.ChildTask)
{
if (child.Task?.Date > maxDate) maxDate = child.Task.Date;
foreach (var taskGroup in child.ChildTask)
{
var childMax = GetMaxDate(taskGroup);
if (childMax > maxDate) maxDate = childMax.Date;
}
}
return maxDate;
}
Upvotes: 2