【问题标题】:query nested objects with LINQ使用 LINQ 查询嵌套对象
【发布时间】:2016-09-02 20:06:32
【问题描述】:

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

Division 对象包含一个 Branch 对象列表。
每个分支对象都包含一个部门对象列表。
每个 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。

感谢您的时间和考虑。

【问题讨论】:

  • 你想要 SelectMany

标签: c# vb.net linq lambda


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    你可以使用 SelectMany

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多