c# - 有没有办法调用在 foreach 函数 block 中声明的变量?

标签 c#

例如

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/

相关文章:

c# - 获取字符串中重复字符的索引

c# - Unity - "SetDestination"只能在已放置在 NavMesh 上的事件代理上调用。 UnityEngine.NavMeshAgent :SetDestination(Vector3)

c# - 在 C# .NET 中为蓝牙创建虚拟 COM 端口

c# - 异步函数可以内联吗?

c# - WPF- 将更改事件添加到自动生成的 DataGridComboBoxColumn

c# - 从 Salesforce Apex 标注捕获/查看 http POST

c# - 在解析期间确定依赖项的目标类型

c# - 为 HashSet<Tuple<TO, int>> 编写 IEqualityComparer

c# - 如何根据另一个下拉列表启用和禁用下拉列表项

c# - IIS7 中所有新的 aspx 页面上的解析器错误