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
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<>
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.)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With