leora leora - 4 months ago 16
C# Question

In C#, what is the best way to get a list of parent Ids recursively?

In C#, I have an Team object.

  • A team object has an Id.

  • A team also has attribute called Parent which is also a team object

I want to figure out a way where given a team, i have a function that passes in that team and returns an array that includes that team Id as well as all of its parents recursive (parent, grandparent, greatgrandparent, etc) team id.

So for example, lets say i have the following teams

  • LowLevelTeam (id = 6)

  • NextLevelTeam (id = 10)

  • HighLevelTeam (id = 12)

So If i pass in LowLevelTeam, this function would return an array with (6, 10, 12)

If I pass in NextLevelTeam, this function would return an array (10, 12)

If I pass in HighLevelTeam, this function would return an array ( 12)

In my case i have several hundred "levels" but the above example should highlight the request.


Non-recursive solution is really easy.

List<int> GetTeamAncestors(Team team)
    var ancestors = new List<int>() {team.Id};

    while (team.Parent != null) // how do I know if the team has a parent?
        team = team.Parent;
    return ancestors;

That's the basic idea.