Dagrooms
Dagrooms

Reputation: 1564

Get Keys from C# Dictionary

One would imagine this would be a pretty simple task, yet I'm getting a System.InvalidOperationException when I run this code:

Dictionary<string, bool> TableExists = new Dictionary<string, bool>();
//... fill the dictionary
foreach(string value in TableExists.Keys){/*Do something*/}

It is supposed to iterate through the keys of the dictionary TableExists, but I get the Invalid Operation Exception at the foreach line. Am I using any Dictionary operations incorrectly? What is the proper way to work through the keys of a C# Dictionary if so?

Edit:

Yes, I was attempting to change some values corresponding to dictionary keys, getting a Collection was modified error.

Upvotes: 0

Views: 307

Answers (1)

AlexD
AlexD

Reputation: 32616

Certain operations are not allowed within foreach (emphasis mine):

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects.

If you are trying to add or remove the dictionary elements within foreach you may get

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Upvotes: 9

Related Questions