You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用For循环批量创建customerclass的orderdetails列表项

解决批量添加OrderDetails到Customers类的问题

你当前的循环代码存在核心问题:每次循环都会给customerclass.items重新赋值一个仅包含当前循环生成的单个orderdetails的新列表,最终只会保留最后一次循环的结果,之前的明细都会被覆盖。以下是两种正确的实现方式:

方法一:初始化列表后循环添加

先初始化items列表,再通过循环逐个创建并添加orderdetails实例,适合需要在循环内执行额外逻辑的场景:

' 先初始化列表(确保不是Nothing)
customerclass.items = New List(Of customerclass.orderdetails)()

' 循环生成并添加明细项
For x = 0 To orderdetailcounter.Value ' 示例循环2次(若要生成2个明细,可调整为To 1,根据实际需求修改)
    Dim detail = New customerclass.orderdetails With {
        .property1 = "example value " & x,
        .property2 = "another example value " & x
    }
    customerclass.items.Add(detail)
Next

方法二:用LINQ一次性生成列表

通过LINQ的Enumerable.Range直接批量生成所有orderdetails实例并转为列表,代码更简洁:

customerclass.items = Enumerable.Range(0, orderdetailcounter.Value + 1) _
    .Select(Function(x) New customerclass.orderdetails With {
        .property1 = "example value " & x,
        .property2 = "another example value " & x
    }) _
    .ToList()

注:Enumerable.Range(0, count)的第二个参数是生成元素的总数量,比如要生成0、1两个序号的明细,就传入2,对应orderdetailcounter.Value +1(若orderdetailcounter.Value为1),可根据实际需要生成的明细数量调整参数。

内容的提问来源于stack exchange,提问作者Christopher Faulkner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:32:09