Modify dictionary

0

Could someone teach me how to modify the properties of an object while I'm going through the dictionary? For example, when I get the key 2 or dia 2 , I need to modify the property dinero .

Dim persona1 As New Persona
persona1.Dia = 1
persona1.Dinero = 200

Dim persona2 As New Persona
persona2.Dia = 2
persona2.Dinero = 0

Dim persona3 As New Persona
persona3.Dia = 3
persona3.Dinero = 300

Dim persona4 As New Persona
persona4.Dia = 4
persona4.Dinero = 500

Dim dictionary As New Dictionary(Of Integer, Persona)
dictionary.Add(1, persona1)
dictionary.Add(2, persona2)
dictionary.Add(3, persona3)
dictionary.Add(4, persona4)

Dim pair As KeyValuePair(Of Integer, Persona)
For Each pair In dictionary
    Console.WriteLine("{0}, {1}", pair.Key, pair.Value)
Next
    
asked by magi0 20.11.2016 в 02:43
source

1 answer

2

I do not see the complication. You simply add a condition within For Each .

For example, if you want to do it by Key = 2 :

For Each pair In dictionary
    If pair.Key = 2 Then
        pair.Value.Dinero = 1000
    End If
Next

Or if you want to do it by Dia = 2 :

For Each pair In dictionary
    If pair.Value.Dia = 2 Then
        pair.Value.Dinero = 1000
    End If
Next

But it's best not to go through the dictionary using a loop. You can access Key = 2 directly like this:

dictionary(2).Dinero = 1000
    
answered by 20.11.2016 / 02:49
source