[英]Reduce multiple foreach loops in code C#
I have wrote a really messy code, just because I did not had an idea how to loop through the multiple list of objects.我写了一个非常混乱的代码,只是因为我不知道如何遍历多个对象列表。
Code is working what it suppose to do, but I am not confident with it.代码正在按预期工作,但我对它没有信心。 Does someone has an idea how this kind of code can be refactored so it is more readable?
有人知道如何重构这种代码以使其更具可读性吗?
foreach (var outlet in merchant.Outlets)
{
if (outlet != null)
{
foreach (var terminal in merchant.Terminals)
{
if (terminal != null)
{
foreach (var agreement in terminal.AssociateAgreements)
{
var bankInfo = new Bank();
if (agreement != null)
{
bankInfo.UniqueID = AgreementUniqueCode + agreement.ID;
bankInfo.BankBIC = agreement.BankAccountInformation.SwiftBIC;
bankInfo.BankName = agreement.BankAccountInformation.BankName;
bankInfo.Address =
AddressEntityToAddress(agreement.BankAccountInformation.BankAddress,
BankingType);
bankInfo.type = BankType;
}
banksAccountInformation.Add(bankInfo);
}
}
}
}
}
You could use LINQ, especially SelectMany
and Where
:您可以使用 LINQ,尤其是
SelectMany
和Where
:
List<Bank> banksAccountInformation = merchant
.Where(m => m.Outlets != null && m.Terminals != null)
.SelectMany(m => m.Terminals
.SelectMany(t => t.AssociateAgreements
.Where(aa => aa != null)
.Select(aa => new Bank
{
UniqueID = AgreementUniqueCode + aa.ID
// ...
})))
.ToList();
You could also use the linq query syntax:您还可以使用 linq 查询语法:
var outletQuery = from outlet in merchant.Outlets
where outlet != null
select outlet;
var agreementQuery = from terminal in merchant.Terminals
where terminal != null
from agreement in terminal.AssociateAgreements
select agreement;
foreach (var outlet in outletQuery)
{
foreach (var agreement in agreementQuery)
{
ProcessAgreement(agreement);
}
}
If the only thing you want to is drilling down the object hierarchy, then you can use extension methods or linq:如果您只想向下钻取对象层次结构,那么您可以使用扩展方法或 linq:
// here you get a flattened collection of Terminals
merchants.SelectMany( m => m.Terminals)
// here you get a flattened collection of all AssociateAgreements of all Terminals
.SelectMany( t => t.AssociateAgreements)
if i am:如果我是:
foreach (var outlet in merchant.Outlets)
{
if (outlet == null)
continue;
foreach (var terminal in merchant.Terminals)
{
if (terminal == null)
continue;
foreach (var agreement in terminal.AssociateAgreements)
{
if (agreement == null)
continue;
//TODO
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.