Given a list of the following models
public class Team
{
public int TeamId { get; set; }
public int ParentTeamId { get; set; }
}
I
Firstly you will need an object like this, so the Team object might be:
public class Team
{
public int? ParentId { get; set; }
public IEnumerable ChildTeams { get; set; }
}
Then a recursive function:
private IEnumerable BuildTeams(IEnumerable allTeams, int? parentId)
{
var teamTree = new List();
var childTeams = allTeams.Where(o => o.ParentId == parentId).ToList();
foreach (var team in childTeams)
{
var t = new Team();
var children = BuildTeams(allTeams, team.TeamID);
t.ChildTeams = children;
teamTree.Add(t);
}
return teamTree ;
}
The first call passes a null
for parent, and will pull all the teams that have a null parent :), though I notice your teams don't have a null for parent, so not sure how you identify the top level ones currently?