c# - 有没有办法调用在 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
解决方案
在你需要的范围内声明变量。例如:
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()
,并且可能会有性能对此有待考虑。
推荐阅读
- python - How can i insert row into table sqlalchemy object?
- android - 在锁定任务模式下允许访问 USB 设备对话框
- python - 嵌入式环境中的 Python 子进程块
- r - 用于 Phi 系数的 R 循环
- linux - linux内核如何为睡眠进程计时?
- node.js - 在 Sequelize.js 的聚合函数中使用 case-when
- r - 仅用于 4 x 4 图的底部面板的 X 轴标题
- c++ - unique_ptr 中模板和继承的重载解决方案
- angular - 从嵌套的 rxjs 订阅中填充 2 个不同列表的角树结构
- java - 如何修复有关已弃用语法的 Apache Camel WARN