Given the list of the following models
public class Team { public int TeamId { get; set; } public int ParentTeamId { get; set; } }
I am trying to write a recursive linq query that will allow me to get a hierarchy that looks like this:
Team ChildTeams Team Team ChildTeams
I tried many approaches and saw many similar questions, but none of them helped me solve the problem. The last attempt I tried went as follows:
private class TeamGrouping { public int? ParentTeamId { get; set; } public IEnumerable<Team> ChildTeams { get; set; } public IEnumerable<TeamGrouping> Grouping { get; set; } } private IEnumerable<TeamGrouping> ToGrouping(IEnumerable<Team> teams) { return teams.GroupBy(t => t.ParentTeamId, (parentTeam, childTeams) => new TeamGrouping {ParentTeamId = parentTeam, ChildTeams = childTeams}); } private IEnumerable<TeamGrouping> ToGrouping(IEnumerable<TeamGrouping> teams) { return teams.GroupBy(t => t.ParentTeamId, (parentTeam, childTeams) => new TeamGrouping{ParentTeamId = parentTeam, Grouping = childTeams}); }
I passed the list of commands to the first ToGrouping(IEnumerable<Team>) , and then the subsequent returned groups to ToGrouping(IEnumerable<TeamGrouping>) , but this leads to incorrect results.
Anyone have any tips or ideas?
source share