LINQ recursive query to return hierarchical set of groups

前端 未结 3 1426
花落未央
花落未央 2020-12-09 13:08

Given a list of the following models

public class Team
{
    public int TeamId { get; set; }
    public int ParentTeamId { get; set; }
}

I

3条回答
  •  离开以前
    2020-12-09 13:30

    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?

提交回复
热议问题