foreach字典<>值或foreach字典<> [英] foreach Dictionary<>.Values or foreach Dictionary<>
问题描述
我想了解这两种在C#中迭代Dictionary
集合的样式的详细信息:
I want to know the details of this two styles of iterating Dictionary
collections in C#:
Dictionary<X, Y> xydic = new Dictionary<X, Y>();
样式一:
foreach (Y y in xydic.Values) { use y }
样式二:
foreach (var it in xydic) { Y y = it.Value; use y... }
多年来我一直是C ++开发人员(现在我在C#项目中工作),我不知道Dictionary
集合如何工作,内存布局或元素如何迭代的详细信息,所以我想知道:
I've been C++ developer for years (now I'm working in a C# project) and I don't know the details of how the Dictionary
collection works, the memory layout or how the elements are iterated so I'm wondering:
xydic.Values
创建一个临时List<Y>
吗?我没有在文档中看到有关创建临时列表的任何信息.
xydic.Values
creates a temporary List<Y>
? I don't see in the documentation any information about the creation of a temporary list.
如果创建了一个临时列表,这是否意味着对该集合进行了两次迭代:首先创建List<Y>
,其次创建列表本身?
If a temporary list is created wouldn't this mean that the collection is iterated twice: first to create the List<Y>
and second to iterate the list itself?
如果以上问题的答案是肯定的,则第二种样式应该更有效,从而使第一种样式几乎没有用,所以我认为我在某种程度上应该是错误的.
If the the answer to question above is yes, the second style should be more efficient making the first style almost useless so I think that I should be wrong in some way.
我觉得这个问题应该在某个地方回答,但我找不到答案.
I have the feeling that this question should be answered somewhere but I'm unable to locate an answer.
推荐答案
检索Dictionary<,>
的.Values
属性是一项O(1)操作(
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.
在调用GetEnumerator()
时,您将获得嵌套的,嵌套的Dictionary<,>.ValueCollection.Enumerator
结构的实例.它直接通过Dictionary<,>
的private
数组entries
访问条目.
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<,>
.
您可以查看源代码.
因此,您上面的样式一"是一种良好且清晰的处理方式,而没有性能开销.
So your "Style one" above is a good and clear way of doing things, with no performance overhead.
请注意,获取值的顺序是任意的.您不知道基础数组entries
的组织方式,一旦Dictionary<,>
具有许多插入和删除操作,然后再开始进行foreach
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.
但是,样式一"和样式二"的顺序是相同的;两者都以相同的方式访问Dictionary<,>
的私有entries
数组.
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.
这篇关于foreach字典<>值或foreach字典<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!