2011-04-18 107 views
4

如何枚举通过IDictionary?请参阅下面的代码。如何通过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(); 
    } 
} 

回答

6

手册枚举是非常罕见的(相比于foreach,例如) - 我建议的第一件事就是:检查你真的很需要那。但是,由于字典列举为键值对:

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

应该工作。或者如果它是只有的方法变量(不是域),则:

var enumerator = value.GetEnumerator(); 

或更好(因为如果它不是,它可能需要本地处置场):

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

或最佳( “KISS”):

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

但是,你也应该经常更换处置时,任何现有值。另外,一个集合属性是非常罕见的。你真的可能想检查这里没有一个更简单的API ...例如,一个方法把字典作为参数。

+0

感谢马克,我正在与foreach的东西 – Amit 2011-04-18 07:12:49

2

如果你只是想枚举它简单地使用foreach(var item in myDic) ...样品执行看到MSDN Article

4
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 
    } 
} 
+2

一个'IDictionary '不会返回'Dictionary .Enumerator'; p或者,如果具体的实现碰巧是具体的'Dictionary <,>'但不能保证。 – 2011-04-18 07:00:49

+0

@Marc:谢谢你指出:)我已经纠正它。 – abhilash 2011-04-18 07:06:16