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

时间:2014-08-27 11:40:11

标签: c# .net 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;
                    }
                }
            }
        }
    }
}

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

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:2)

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,与toadflakz解决方案不同,它不应该在program.GetProfitCenter() == null时抛出异常。

答案 2 :(得分:1)

它与您已经编写的代码没有什么不同,除非您最后进行了所有过滤。

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();

我不能保证这会有效,但它应该让你知道从哪里开始。