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

本文关键字:一个对象 取对象 获取 LINQ 何编写 查询 | 更新日期: 2023-09-27 18:19:50

我已经将以下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;
                    }
                }
            }
        }
    }
}

只要不存在这样的帐户代码,结果也应该返回null。请帮我为以上循环构建LINQ。

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

使用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();
return (from plant in Plant.ListPlants
from program in plant.GetAllPrograms()
where program.GetProfitCenter() != null
from costCenter in program.GetProfitCenter().GetAllCostCenters()
from account in costCenter.GetAccounts()
where account.Code == Code
select account).FirstOrDefault();

这应该有效,我使用ReSharper功能将foreach转换为LINQ,并且与toflakz解决方案不同,它在program.GetProfitCenter() == null时不应该抛出异常。

这与您已经编写的代码没有什么不同,只是您在最后完成了所有的过滤。

var accounts = 
    from plant in Plant.ListPlants
    from program in plant.GetAllPrograms()
    from costCenter in program.GetProfitCenter().GetAllCostCenters()
    from account in costcenter.GetAccounts()
    where program.GetProfitCenter() != null && 
          account.Code == Code
    select account;
return accounts.FirstOrDefault();

我不能保证这会起作用,但它应该会给你一个从哪里开始的好主意。