I want to know the details of this two styles of iterating Dictionary
collections in C#:
Dictionary xydic = new Dictionary
Retrieving the .Values
property of a Dictionary<,>
is an O(1) operation (documented). The nested type Dictionary<,>.ValueCollection
is a simple wrapper around the dictionary, so there is no iterating in creating it.
On calling GetEnumerator()
, you get an instance of the nested, nested Dictionary<,>.ValueCollection.Enumerator
struct. It acccesses the entries directly through the private
array entries
of the Dictionary<,>
.
You can see the source code.
So your "Style one" above is a good and clear way of doing things, with no performance overhead.
Note that the order in which you get the values, is arbitrary. You do not know how the underlying array entries
is organized, once the Dictionary<,>
has had many insertions and removals before you start foreach
ing it.
However, the order you get with "Style one" and "Style two" is the same; both access the private entries
array of the Dictionary<,>
in the same way.