开发者

How to enumerate through IDictionary

开发者 https://www.devze.com 2023-02-26 19:33 出处:网络
How can I enumerate through an IDictionary? Please refer to the code below. public IDictionary<string, string> SelectDataSource

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开发者_StackOverflow is of type string,string
        IDictionaryEnumerator enumerator = value.GetEnumerator();
    }
 }


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.


Smooth solution

using System.Collections;

IDictionary dictionary = ...;

foreach (DictionaryEntry kvp in dictionary) {
    object key = kvp.Key;
    object value = kvp.Value;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消