首页 > 解决方案 > 有没有办法调用在 foreach 功能块中声明的变量?

问题描述

例如

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

如何使用功能块lineItems外的变量foreach

标签: c#

解决方案


在你需要的范围内声明变量。例如:

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()在 a 内调用,.Select()直到您将所有记录具体化到内存中,例如使用 a .ToList(),并且可能会有性能对此有待考虑。


推荐阅读