Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate through IDictionary

Tags:

c#

How can I enumerate through an IDictionary? Please refer to the code below.

 public IDictionary<string, string> SelectDataSource
 {
    set
    {
        // This line does not work because it returns a generic enumerator,
        // but mine is of type string,string
        IDictionaryEnumerator enumerator = value.GetEnumerator();
    }
 }
like image 840
Amit Avatar asked Apr 18 '11 06:04

Amit


3 Answers

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.

like image 114
Marc Gravell Avatar answered Sep 29 '22 03:09

Marc Gravell


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
    }
}
like image 34
abhilash Avatar answered Sep 29 '22 03:09

abhilash


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

like image 45
Saeed Amiri Avatar answered Sep 29 '22 02:09

Saeed Amiri