2017-04-17 65 views
0

我正在使用类似于下面的结构。我需要遍历'Persons'ArrayList并将每个薪水设置为100,同时保持LastNames不变。VB.Net如何更新ArrayList中的每个条目?

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'复制到第二个临时数组列表中,然后删除原数据列表中的条目,但我无法弄清楚如何更改每个人的工资,并在保留'LastName'的同时'再次'添加'价值观就像它们最初一样。

+1

具有合适属性的类比这里的结构更合适;同样,一个类型化的集合像一个'List(Of T)'来代替无类型的ArrayList。然后循环 – Plutonix

+0

@Plutonix说什么。 ArrayList属于C#没有泛型的日子。它已弃用,获得列表。除非您必须与使用它的旧API接口,否则不应在目标.NET> = 2.0的新代码中使用ArrayList。从http://stackoverflow.com/a/2309699/832052 – djv

+1

[在类和结构之间选择](https://msdn.microsoft.com/en-us/library/ms229017(v = vs.110).aspx) – Plutonix

回答

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 

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

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 
+0

其实Plutonix说的是'一个具有正确属性的类' - 这只是一些私有变量。 – Plutonix

0

建议的循环:

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

没有工作,因为它没有永久写入新的价值,“人”,但经过进一步搜索,我发现一个循环,它:

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

我希望这可以帮助别人。我也实施了LIST的想法 - 谢谢。