VB.Net如何更新ArrayList中的每个条目?

时间:2017-04-17 17:53:55

标签: vb.net arraylist foreach

我正在使用类似于下面的结构。我需要遍历'Persons'ArrayList并将每个薪水设置为100,同时保留LastNames。

Structure Person
    Dim LastName As String
    Dim salary As Integer
End Structure

public class Test
    public Shared Sub Main
        Dim Persons As New ArrayList
        Dim Person As New Person

        With Person
            .LastName = "Smith"
            .salary = 50
        End With
        Persons.Add(Person)

        With Person
            .LastName = "Jones"
            .salary = 20
        End With
        Persons.Add(Person)

        With Person
            .LastName = "Brown"
            .salary = 80
        End With
        Persons.Add(Person)

    End Sub
End class

我意识到一个简单的For Each循环在这里不起作用。我可以将每个'Person'复制到第二个临时arraylist,然后删除原始arraylist中的条目,但我无法弄清楚如何更改每个人的工资并再次'添加',同时保留'LastName'最初的价值观。

3 个答案:

答案 0 :(得分:2)

使用List(Of Person)代替ArrayList(隐式Of Object)。

只需编写一个辅助函数来简化添加。您可以轻松地遍历List(Of Person),因为它现在被键入Person

Structure Person
    Dim LastName As String
    Dim salary As Integer
End Structure

Sub Main()
    Dim Persons As New List(Of Person)()
    AddPerson(Persons, "Smith", 50)
    AddPerson(Persons, "Jones", 20) ' poor Jonesy
    AddPerson(Persons, "Brown", 80)
    For Each person In Persons
        person.salary = 100
    Next

End Sub

Public Sub AddPerson(persons As List(Of Person), lastName As String, salary As Integer)
    persons.Add(New Person() With {.LastName = lastName, .salary = salary})
End Sub

另一点

您的原始代码适用于For Each循环

For Each p As Person In Persons
    p.salary = 100
Next

但使用ArrayList的风险在于您可以无误添加任何对象。然后,如果您没有受到纪律处分,只能在其中添加Person,那么在将项目转换回Person时可能会遇到问题。例如

Persons.Add(New Object)

For Each p As Person In Persons
    p.salary = 100
Next

会迭代,直到循环结束时遇到New Object,然后会导致运行时错误。 List(Of Person)会阻止它首先被添加,这就是为什么它总是优先于ArrayList进行新开发。

答案 1 :(得分:1)

在这种情况下,班级可能会更好。此外,您可以将Salary的默认值设置为100,以便每个对象都具有默认值(不需要在循环中稍后分配)。

Public Class Person
  Dim LastName As String = ""
  Dim salary As Integer = 100

  Public Sub New()
      '
  End Sub

  Public Sub New(ByVal Last_Name As String, ByVal Salary As Integer)
      Me.LastName = Last_Name
      Me.salary = Salary
  End Sub
End Class

答案 2 :(得分:0)

建议的循环:

For Each p As Person In Persons
    p.salary = 100
Next

没有工作,因为它没有永久性地将新值写入' Persons',但在进一步搜索后我发现了一个循环:

    For x = 0 To Persons.Count - 1
        Dim p As Person = Persons(x)
        p.salary = 100
        Persons(x) = p
    Next

我希望这有助于其他人。我也实施了LIST的想法 - 谢谢。