Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using a Dictionary<long, bool> and I want to change it while I enumerate through it, but it seems this is not allowed. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...