Link to home
Start Free TrialLog in
Avatar of Philippe Renaud
Philippe RenaudFlag for Canada

asked on

Iterate a dictionnary to change values

Hello EE,

I need to update many values of a Dictionnary .. to do that, I was thinking of iterating it but then realized I cannot change value if I do this.

So I found a way like this :

        For x As Integer = 0 To finalDict2.Count - 1
            Dim test As String = finalDict2.ElementAt(x).Key
            Dim testV As Integer = finalDict2.ElementAt(x).Value

            If a.BinarySearch(test) < 0 Then
                finalDict2.Remove(test)
                finalDict2.Add(test, testV + 1)
            Else
                finalDict2.Remove(test)
                finalDict2.Add(test, 0)
            End If
        Next

Open in new window


Overall what I do is, if a value matches a variable, I want to put his dicitonnary value back to 0
OR if does not match, i want to increase its value by 1

so to eithe rput to 0 or do + 1, I remove and re-add in dictionnary

but all this takes to much time... im sure its not efficient..
any better idea ?
ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of p_davis
p_davis

also... with a for or foreach you might want to use local variables outside the loop i.e.
  Dim test As String
            Dim testV As Integer

you can also use linq to to get an index of an item that has the key/value that you want

you can iterate/enumerate on a keyvaluepair btw
with c# anyway... i assume there is something similar with vb
Why do you need removing and adding values with same key? You can simly change value:
For Each key In finalDict2.Keys
    If a.BinarySearch(key) < 0 Then
        finalDict2(key)+= 1
    Else
        finalDict2(key) = 0
    End If
Next

Open in new window