[英]How do I create a list object that contains a list of another object type using from within a query using linq and c#
[英]How to write LINQ query for getting object from another object using C#?
我將以下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。
使用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,與toadflakz解決方案不同,它不應該在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();
我不能保證這會起作用,但它應該讓你知道從哪里開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.