Dictionary navigation <string, int> C #

What is the best way to navigate a dictionary? I used the code below when I had an IDictionary:

Suppose I have an IDictionary named freq

IEnumerator enums = freq.GetEnumerator();
while (enums.MoveNext())
{
    string word = (string)enums.Key;
    int val = (int)enums.Value;
    .......... and so on

}

but now I want to do the same using the dictionary

+5
source share
3 answers

The operator foreachiterates over the counters automatically.

foreach (KeyValuePair<string,int> entry in freq) {
    string word = entry.Key;
    int val = entry.Value;
    .......... and so on

}
+4
source

The default enumerator from foreachprovides you with KeyValuePair<TKey, TValue>:

foreach (var item in dictionary)
// foreach (KeyValuePair<string, int> item in dictionary)
{
    var key = item.Key;
    var value = item.Value;
}

It just compiles into code that works directly with the enumerator, as in your old code.

Or you can directly list .Keysor .Values(but in this case you only get the key or value):

foreach (var key in dictionary.Keys)

foreach (var val in dictionary.Values)

linq :

# linq < gt;

+15

, Dictionary, foreach :

foreach (var entry in dictionary)
{
    string key = entry.Key;
    int value = entry.Value;
    // Use them...
}

:

using (var iterator = dictionary.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        var entry = iterator.Current;
        string key = entry.Key;
        int value = entry.Value;
        // Use them...
    }
}

It is very rarely useful to explicitly invoke GetEnumeratorand iterate. This is suitable in several cases, for example, when you want to treat the first value differently, but if you treat all the records the same way, use foreach.

(Note that this is really equivalent to using varhere, but not equivalent to declaring IEnumerator<KeyValuePair<string, int>>- it will actually use a nested Dictionary.Enumeratorstruct. This is a detail that you usually don't need to worry about.)

+8
source

All Articles