none
Can one replace a value in a Directory(Of TKey, TValue)? RRS feed

  • Question

  • I want to replace the value for a particular key in a Directory(Of TKey, TValue) when I know that the key already exists.

    It's in a loop of the type:

    for each KVP in Directory
      if NeedsChanging(KVP.Value)
        Directory(KVP.Key)=NewValue
      end if
    next
    

    But I get an error as this also potentially updates the key and destroys the loop. Is there any way round this, apart from batching up the  replacements in a list during the loop and updating the directory entries in a separate loop?

    Or is there a Replace(TKey, TValue) method for Directory which I've not managed to find?



    Peter

    Thursday, September 11, 2014 8:32 AM

Answers

  • "Is there any way round this, apart from batching up the  replacements in a list during the loop and updating the directory entries in a separate loop?"

    Unfortunately you don't have much of choice, the enumerator invalidation rules are too restrictive and you have to batch as you described. Alternatively you could throw some LINQ extensions into the mix to make things easier:

    For Each KVP In Directory.Where(Function(p) NeedsChanging(p.Value)).ToList()
        Directory(KVP.Key) = NewValue
    Next
    
    The ToList is intended to produce a list of KVP that can be enumerated safely while the dictionary is modified. If you don't need the KVP.Value and the number of values that need to be changes is potentially large then consider adding a Select(Function(p) p.Key) after Where to minimize the memory required by the list.

    • Marked as answer by ptoye Thursday, September 11, 2014 9:23 AM
    Thursday, September 11, 2014 9:07 AM
    Moderator

All replies

  • "Is there any way round this, apart from batching up the  replacements in a list during the loop and updating the directory entries in a separate loop?"

    Unfortunately you don't have much of choice, the enumerator invalidation rules are too restrictive and you have to batch as you described. Alternatively you could throw some LINQ extensions into the mix to make things easier:

    For Each KVP In Directory.Where(Function(p) NeedsChanging(p.Value)).ToList()
        Directory(KVP.Key) = NewValue
    Next
    
    The ToList is intended to produce a list of KVP that can be enumerated safely while the dictionary is modified. If you don't need the KVP.Value and the number of values that need to be changes is potentially large then consider adding a Select(Function(p) p.Key) after Where to minimize the memory required by the list.

    • Marked as answer by ptoye Thursday, September 11, 2014 9:23 AM
    Thursday, September 11, 2014 9:07 AM
    Moderator
  • Thanks Mike. I hoped I was being stupid, but it seems that Microsoft are instead..... It seems odd that there's no "replace" method.

    The numbers are small so I'll just make a list.


    Peter

    Thursday, September 11, 2014 9:23 AM