浏览字典的更好方法是什么?当我有IDictionary时,我曾经使用下面的代码:
假设我有IDictionary命名 freq
IEnumerator enums = freq.GetEnumerator();
while (enums.MoveNext())
{
string word = (string)enums.Key;
int val = (int)enums.Value;
.......... and so on
}
Run Code Online (Sandbox Code Playgroud)
但现在,我想用字典做同样的事情
Ada*_*rth 15
a中的默认枚举器foreach为您提供KeyValuePair<TKey, TValue>:
foreach (var item in dictionary)
// foreach (KeyValuePair<string, int> item in dictionary)
{
var key = item.Key;
var value = item.Value;
}
Run Code Online (Sandbox Code Playgroud)
这只是编译成直接与枚举器一起使用的代码,就像在旧代码中一样.
或者你可以枚举.Keys或.Values直接枚举(但在这种情况下你只得到一个键或一个值):
foreach (var key in dictionary.Keys)
foreach (var val in dictionary.Values)
Run Code Online (Sandbox Code Playgroud)
或者当然linq对词典起作用:
那么你可以做同样的事情Dictionary,但foreach在两种情况下都会更清洁:
foreach (var entry in dictionary)
{
string key = entry.Key;
int value = entry.Value;
// Use them...
}
Run Code Online (Sandbox Code Playgroud)
这相当于:
using (var iterator = dictionary.GetEnumerator())
{
while (iterator.MoveNext())
{
var entry = iterator.Current;
string key = entry.Key;
int value = entry.Value;
// Use them...
}
}
Run Code Online (Sandbox Code Playgroud)
这是非常罕见有用的显式调用GetEnumerator并重复自己.它适用于少数情况,例如当您想要以不同方式处理第一个值时,但如果您要以相同方式处理所有条目,请使用foreach.
(注意它实际上相当于在var这里使用,但不等同于声明IEnumerator<KeyValuePair<string, int>>- 它实际上将使用嵌套Dictionary.Enumerator结构.这是你通常不需要担心的细节.)
该foreach语句自动遍历枚举器。
foreach (KeyValuePair<string,int> entry in freq) {
string word = entry.Key;
int val = entry.Value;
.......... and so on
}
Run Code Online (Sandbox Code Playgroud)