【问题标题】:VB.net Updating a List variable inside of a For Each LoopVB.net 在 For Each 循环中更新列表变量
【发布时间】:2016-09-28 17:59:49
【问题描述】:
Dim aProductos As List(Of Producto)
Dim aRegistros As New List(Of Registro)
Dim selectedProd As New Producto

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Add to cart
    Dim insert As Boolean = True

问题从这里开始 vvv

    For Each reg In aRegistros
        If (reg.id_prod = Integer.Parse(lbCodigo.Text)) Then

            Dim r As New Registro
            r.id_prod = reg.id_prod
            r.cantidad = reg.cantidad + Integer.Parse(nudUni.Value.ToString)
            reg = r
            insert = False
        End If
    Next

问题在这里结束^^^

    If insert Then
        Try
            Dim r As New Registro
            r.id_prod = selectedProd.cod
            r.cantidad = Integer.Parse(nudUni.Value.ToString)
            aRegistros.Add(r)
        Catch ex As Exception
            MsgBox("Create and insert register: " + ex.Message)
        End Try
    End If
    MostrarFactura()
End Sub

Private Sub MostrarFactura() << Updates a listview to see the products you got
    listaProd.Items.Clear()
    For Each registro In aRegistros
        For Each producto In aProductos
            If registro.id_prod = producto.cod Then
                MsgBox(registro.cantidad)
                listaProd.Items.Add(producto.nombre + " --- " + registro.cantidad.ToString + " -> " + (producto.precio * registro.cantidad).ToString + "€")
            End If
        Next
    Next
End Sub

问题是我更新了“reg”,但是当循环完成时,reg 没有更新列表中的值

提前致谢:S

【问题讨论】:

  • 您无法从已使用 foreach 开始枚举的列表中添加/删除。
  • 那我可以用什么代替呢?也许只是一个while循环?
  • 可以改变当前reg变量的属性。 reg.cantidad = reg.cantidad + Integer.Parse(nudUni.Value.ToString);
  • 刚刚从创建对象和插入对象切换到只是更改变量,它会更改它,并且当我在循环内时我可以打印它,但当我在循环之外时不能打印,就在MostrarFactura() 之前的行

标签: vb.net loops for-loop each


【解决方案1】:

您可以使用整数来指定列表中的位置,而不是使用For Each

For x = 0 to aRegistros.Count -1
  Dim reg = aRegistros(x)
  Dim r As New Registro
  r.id_prod = reg.id_prod
  r.cantidad = reg.cantidad + Integer.Parse(nudUni.Value.ToString)
  aRegistros(x) = r
  insert = False
Next

【讨论】:

  • 非常感谢戴夫,我没有意识到这一点,因为我不记得有一个简单的索引 for 循环!
  • 只是说,问题似乎是我正在使用结构,我猜它们不能在列表或类似的东西内更改。事实是我将它们更改为真正的课程并且效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-17
  • 2019-05-04
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
相关资源
最近更新 更多