jonathana jonathana - 4 months ago 38
C# Question

query nested objects with LINQ

I have an instance object of Division class.

Division object holds a list of Branch objects.

Each branch object holds a list of Department objects.

Each Department object holds list of Team objects.

just to make it clear I can do that:

int MakeItClear = DivisionObject.ListOfBranches[5]

Each object has

My wish is create a function that will return a list of team names by passing a parameter of Branch.ID using LINQ.

basically I want to do that using LINQ:

public static List<string> getBranchTeamNames(ref Sales.Division obj, int BranchID)
List<string> result = new List<string>();
foreach (Sales.Branch b in obj.allBranches)
if (b.branchID == BranchID)
foreach (Sales.Department d in b.allDepartmentsManagers)
foreach (Sales.Team t in d.allTeams)


return result;

i would be happy for some guidance, does not matter if its c# or

thank you for your time and consideration.


Try this:

return obj.allBranches
    .Where(x => x.branchID == BranchID)
    .SelectMany(x => x.allDepartmentsManagers)
    .SelectMany(x => x.allTeams)
    .Select(x => x.teamName)