使用LINQ

时间:2016-09-02 20:06:32

标签: c# vb.net linq lambda

我有一个Division类的实例对象。

分区对象包含分支对象列表 每个分支对象都包含一个Department对象列表 每个Department对象都包含Team对象列表。

只是为了表明我能做到这一点:

int MakeItClear = DivisionObject.ListOfBranches[5]
                                .ListOfDepartments[4]
                                .ListOfTeam[3]
                                .SomeIntegerProperty;

每个对象都有IDName属性

我希望创建一个函数,通过使用LINQ传递Branch.ID参数来返回团队名称列表。

基本上我想用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)

                {
                    result.Add(t.teamName);
                }
            }

             break;
        }          
    }
    return result;
}

我会很乐意提供一些指导,无论是c#还是vb.net都无所谓。

谢谢你的时间和考虑。

2 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分:0)

您可以使用SelectMany

var teamNames = division.Branches.First(branch => branch.Id.Equals(branchId)).Departments.SelectMany(department => department.Teams.Select(team => team.Name));

相关问题