Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate through dictionary <string, int> c#

Tags:

c#

c#-4.0

What is the better way to Navigate through a dictionary ? I used to use the code below when i had IDictionary:

Assume that I have 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 thing using dictionary

like image 735
Jone Mamni Avatar asked May 08 '12 12:05

Jone Mamni


3 Answers

The default enumerator from a foreach gives you a KeyValuePair<TKey, TValue>:

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

This simply compiles into code that works directly with the enumerator as in your old code.

Or you can enumerate the .Keys or .Values directly (but you only get a key or a value in that case):

foreach (var key in dictionary.Keys)

foreach (var val in dictionary.Values)

And or course linq works against dictionaries:

C# linq in Dictionary<>

like image 190
Adam Houldsworth Avatar answered Oct 10 '22 11:10

Adam Houldsworth


Well you could do the same thing with Dictionary, but it would be cleaner to use foreach in both cases:

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

This is equivalent to:

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

It's very rarely useful to explicitly call GetEnumerator and iterate yourself. It's appropriate in a handful of cases, such as when you want to treat the first value differently, but if you're going to treat all entries the same way, use foreach.

(Note that it really is equivalent to using var here, but not equivalent to declaring an IEnumerator<KeyValuePair<string, int>> - it will actually use the nested Dictionary.Enumerator struct. That's a detail you usually don't need to worry about.)

like image 29
Jon Skeet Avatar answered Oct 10 '22 12:10

Jon Skeet


The foreach statement iterates automatically through enumerators.

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

}
like image 38
Olivier Jacot-Descombes Avatar answered Oct 10 '22 13:10

Olivier Jacot-Descombes