Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# public static dictionary

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?

like image 713
user2613018 Avatar asked Sep 25 '26 15:09

user2613018


1 Answers

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())
like image 158
Ulugbek Umirov Avatar answered Sep 28 '26 03:09

Ulugbek Umirov