.NET Framework Bookmark and Share   
 index > .NET Base Class Library > why am i getting "Collection was modified" error?
 

why am i getting "Collection was modified" error?

Here is my code:

            var dict = new Dictionary<string, int>();
            dict["1"] = 1;
            var toDelete = dict.Where(x => true);
            foreach (var kvpair in toDelete)
            {
                dict.Remove(kvpair.Key);
            }            

I don't see how I'm modifyingtoDelete in my foreach loop...Can anyone explain why this is happening?

Thanks,
-Vivek.

vivmaha2
The declaration of a query expression just declares a query, but does not evaluate it. It's a kind of lazy evaluation.
That's why you have to call methods such as ToList() or ToArray() to force immediate query evaluation.
  • Marked As Answer byvivmaha2 Friday, August 07, 2009 5:53 PM
  •  
nikho

If i use toDelete.ToArray() for the enumeration, no exception is thrown.
I guess whatever default representation Where() was returning stores back pointers and messes with the original container.

vivmaha2
The declaration of a query expression just declares a query, but does not evaluate it. It's a kind of lazy evaluation.
That's why you have to call methods such as ToList() or ToArray() to force immediate query evaluation.
  • Marked As Answer byvivmaha2 Friday, August 07, 2009 5:53 PM
  •  
nikho

You can use google to search for other answers

Custom Search

More Threads

• Changing charset of runtime so that kernel pinvoke resolved to unicode versions
• how to convet array in to string
• Naming conventions for extension classes
• How can I store multiple values in a collection object?
• Need Help With a WUA App Plz
• how to detect form feed, line feed.....
• .Item property doesn't exist for ArrayLists???
• How encryption keys should be managed?
• ServiceInstaller
• Serial Port communications seem to slow down when application is in focus.