foreach Dictionary<>.Values or foreach Dictionary<>

后端 未结 4 1474
忘掉有多难
忘掉有多难 2021-01-07 06:54

I want to know the details of this two styles of iterating Dictionary collections in C#:

Dictionary xydic = new Dictionary

        
4条回答
  •  醉梦人生
    2021-01-07 07:26

    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 foreaching 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.

提交回复
热议问题