I'm getting a collection of KeyValuePairs by using the Enumerable.Where method with a dictionary. After I get the collection I try to iterate through the collection of keys to remove the keys I found using the where method from the dictionary but am getting a 'Collection was modified; enumeration operation may not execute.' exception when I try to modify the dictionary.
I'm confused about why this is happening, since I'm not actually iterating through the dictionary anymore!
fileDict is a dictionary(of string, string) containing a list of files. The code block works fine if I remove the lines which modify the dictionary.
I'm guessing that the Enumerable.Where method continues to run even though it's already returned values? I hope someone can explain!
Dim oldKeys As IEnumerable(Of KeyValuePair(Of String, String)) = fileDict.Where(Function(grepDict) Regex.Match(grepDict.Key, fixPath(e.OldFullPath)).Success)
Console.WriteLine("oldkeys count " & oldKeys.Count)
For Each s As KeyValuePair(Of String, String) In oldKeys
Console.WriteLine("oldkey " & s.Key & "," & s.Value)
tempStr = s.Value
fileDict.Remove(s.Key)
fileDict.Add(fixPath(e.FullPath), Regex.Replace(tempStr, fixPath(e.OldFullPath), fixPath(e.FullPath)))
Next
Dim newKeys As IEnumerable(Of KeyValuePair(Of String, String)) = fileDict.Where(Function(grepDict) Regex.Match(grepDict.Key, fixPath(e.FullPath)).Success)
For Each s As KeyValuePair(Of String, String) In newKeys
Console.WriteLine(s.Key & "," & s.Value)
Next