例如
List<BursaryPaymentSplitting> splitAccount = new List<BursaryPaymentSplitting>();
foreach ( var lineItem in splitAccount)
{
var lineItems = new RemitaSplit {
lineItemsId = lineItem.BursaryPaymentSplittingId.ToString(),
beneficiaryName = lineItem.AccountName,
beneficiaryAccount = lineItem.AccountNumber,
bankCode = lineItem.BankCode,
beneficiaryAmount = lineItem.Amount.ToString(),
deductFeeFrom = lineItem.DeductFeeFrom.ToString()
};
}
我如何在 foreach
函数 block 之外使用变量 lineItems
最佳答案
在您需要的范围内声明变量。例如:
RemitaSplit lineItems;
foreach (var lineItem in splitAccount)
{
lineItems = new RemitaSplit { /.../ };
}
// Here you can access the lineItems variable.
// Though it *might* be NULL, your code should account for that.
虽然这里的奇怪之处在于您一遍又一遍地覆盖同一个变量。为什么?您的意思是要拥有对象的集合 而不是只有一个对象吗?是这样的吗?:
var lineItems = new List<RemitaSplit>();
foreach (var lineItem in splitAccount)
{
lineItems.Add(new RemitaSplit { /.../ });
}
// Here you can access the lineItems variable.
// And this time it won't be NULL, though it may be an empty collection.
可以简化为:
var lineItems = splitAccount.Select(lineItem => new RemitaSplit { /.../ });
在这种情况下如何使用 LINQ 进行简化将取决于您在哪里/如何填充 splitAccount
。我假设问题中的示例只是显示该变量类型的人为代码行,因为如果那是确切的代码,那么该循环当然永远不会迭代空列表。
重点是,如果 splitAccount
是一个表达式树,它最终会具体化来自后备数据源的数据,您可能无法直接调用 new RemitaSplit()
在 .Select()
中,直到您将所有记录具体化到内存中,例如使用 .ToList()
,并且可能需要考虑性能.
关于c# - 有没有办法调用在 foreach 函数 block 中声明的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58503223/