How to enumerate through IDictionary

Manual enumeration is very rare (compared to foreach, for example) - the first thing I'd suggest is: check you really need that. However, since a dictionary enumerates as key-value-pair:

IEnumerator<KeyValuePair<string,string>> enumerator = value.GetEnumerator();

should work. Or if it is only a method variable (not a field), then:

var enumerator = value.GetEnumerator();

or better (since if it isn't a field it probably needs local disposal):

using(var enumerator = value.GetEnumerator())
{ ... }

or best ("KISS"):

foreach(var pair in value)
{ ... }

However, you should also always dispose any existing value when replaced. Also, a set-only property is exceptionally rare. You really might want to check there isn't a simpler API here... for example, a method taking the dictionary as a parameter.


foreach(var keyValuePair in value)
{
     //Do something with keyValuePair.Key
     //Do something with keyValuePair.Value
}

OR

IEnumerator<KeyValuePair<string,string>> enumerator = dictionary.GetEnumerator();

using (enumerator)
{
    while (enumerator.MoveNext())
    {
        //Do something with enumerator.Current.Key
        //Do something with enumerator.Current.Value
    }
}

if you just want enumerate it simply use foreach(var item in myDic) ... for sample implementation see MSDN Article.

Tags:

C#