2017-04-17 58 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的想法 - 謝謝。