Modifying .NET Dictionary while Enumerating through it

I`m using a Dictionary and I want to change it while I Enumerate through it, but it seems this is not allowed. How can I do this?

Thanks

Answers


You should store the key or object you want to delete and break the loop, and then use remove method to delete the object from dictionary.

Hope this helps


Don't, basically. It's explicitly not supported. From the docs for Dictionary<,>.GetEnumerator():

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.

Typically the best way is to remember the modifications you want to make, and then perform them afterwards. Or you could take a copy of the dictionary to start with and then iterate through that while you modify the original. If you could give us more information about what you're trying to do, that would help.

Having said this, the new ConcurrentDictionary class in .NET 4.0 does permit this - but the results of the iteration aren't guaranteed - you may see the changes while you're iterating, or you may not.


I answered it here with respect to queue's but the answer is the same. You can't enumerate with foreach and modify the collection at the same time.


Need Your Help

Record exist in zf2 with clause

php database zend-framework2 validation

My user table has following columns and data.

Performance of populating new column in sqlite with python

python sqlite

I'm updating an sqlite database to have a new column bin that is filled with the numbers 0 to 100. I've written a simple script that illustrates some performance issues I'm having:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.