So I'm trying to make a publicly accessible dictionary for my entire program to access, I created that under my Form as such:
public static Dictionary<string, int> categories = new Dictionary<string, int>
{
{"services", 0},
{"files", 0},
{"shortcuts", 0},
{"registry", 0},
{"browsers", 0}
};
Now, inside of a private method, I have this code:
foreach (KeyValuePair<string, int> reference in categories)
{
for (int i = 0; i < scanLines.Count; i++)
{
if (scanLines[i].Contains(reference.Key))
{
start = i + 1;
break;
}
}
for (int i = start; i < scanLines.Count; i++)
{
if (scanLines[i].Contains("*"))
{
stop = i - 1;
break;
}
}
// Write the result for the category by subtracting the difference between
// the start and stop variables
categories[reference.Key] = stop - start;
This is basically breaking up a log file in sections to count the lines in between those sections declared in the category dictionary. Now my problem is the line of code
categories[reference.Key] = stop - start;
keeps throwing an Invalid Operation Exception Error. What am I doing wrong here?
You cannot change collection (and Dictionary is collection too) inside foreach loop for it. You can do quick workaround by creating duplicate collection as follows:
foreach (KeyValuePair<string, int> reference in categories.ToList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With