如何编写LINQ查询以使用C#从另一个对象获取对象?

Man*_*yak 2 .net c# linq loops object

我将以下foreach循环转换为LINQ语句.

foreach (Plant plant in Plant.ListPlants)
{
    foreach (Program program in plant.GetAllPrograms())
    {
        if (program.GetProfitCenter() != null)
        {
            foreach (CostCenter costCenter in program.GetProfitCenter().GetAllCostCenters())
            {
                foreach (Account account in costCenter.GetAccounts())
                {
                    if (account.Code == Code)//Code is a parameter
                    {
                        return account;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

只要不存在此类帐户代码,结果应返回null.请帮我构建上述循环的LINQ.

Tim*_*ter 6

使用 SelectMany

var accounts = Plant.ListPlants
    .SelectMany(lp => lp.GetAllPrograms())
    .Where(p => p.GetProfitCenter() != null)
    .SelectMany(p => p.GetProfitCenter().GetAllCostCenters())
    .SelectMany(cc => cc.GetAccounts())
    .Where(acc => acc.Code == Code);
return accounts.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)