浏览字典<string,int> c#

Jon*_*mni 5 c# c#-4.0

浏览字典的更好方法是什么?当我有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对词典起作用:

C#linq in Dictionary <>

  • @JoneMamni:不 - `var`只是给变量一个从赋值的*compile-time*类型推断的类型.执行时没有影响. (2认同)

Jon*_*eet 8

那么你可以做同样的事情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结构.这是你通常不需要担心的细节.)


Oli*_*bes 4

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)

  • `foreach` 在内部调用 `GetEnumerator` 和 `MoveNext`。所以这应该没有什么区别。此外,通用变体应该更快一些,因为不再需要铸件。特别是 `int` 不需要装箱和拆箱。 (2认同)