如何通过IDictionary进行枚举

本文关键字:枚举 IDictionary 何通过 | 更新日期: 2023-09-27 17:50:21

如何通过IDictionary进行枚举?请参阅下面的代码。

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

如何通过IDictionary进行枚举

手动枚举非常罕见(例如,与foreach相比(——我建议的第一件事是:检查您是否真的需要。然而,由于字典枚举为键值对:

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

应该起作用。或者,如果只是一个方法变量(而不是字段(,则:

var enumerator = value.GetEnumerator();

或者更好(因为如果它不是一个油田,它可能需要本地处理(:

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

或最佳("KISS"(:

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

但是,在替换时,还应该始终处置任何现有值。此外,仅限集合的属性非常罕见。您真的可能想检查这里没有更简单的API。。。例如,将字典作为参数的方法。

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

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文章。

平滑解决方案

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