"O.B." <fu******@bellsouth.netwrote in message
news:12*************@corp.supernews.com...
>I need the ability to parse through the values of a Dictionary and remove
certain ones depending on their attribute values. In the example below, an
InvalidOperationException is thrown in the foreach statement when the first
item is removed from the Dictionary.
From looking at Dictionary's methods, I couldn't find anything to create a
copy of the Values before starting the foreach loop. Help?
You cannot modify a container without invalidating all active enumerators -
hence breaking your foreach statement. For a dictionary, what you need to
do is to build a list of keys to be deleted, then use a second loop through
that list to remove items from the dictionary.
static void someTest() {
Dictionary<String, Int32storage = new Dictionary<string, Int32>();
for (int i = 0; i < 100; i++) {
String bar = "Test" + i;
Int32 foo = new Int32();
foo = i;
storage.Add(bar, foo);
}
List<stringkeysToDelete = new List<string>();
foreach (Int32 tmp in storage.Values) {
if ((tmp % 5) == 0) {
String bar = "Test" + tmp;
keysToDelete.Add(bar);
}
}
foreach (string key in keysToDelete) {
storage.Remove(key);
}
}
-cd