简体   繁体   中英

How to enumerate through IDictionary

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();
    }
 }

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
    }
}

如果您只想枚举它,只需使用foreach(var item in myDic) ...示例实现,请参阅MSDN 文章

Smooth solution

using System.Collections;

IDictionary dictionary = ...;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM