2013-02-20 108 views
0

我从ConcurrentDictionary中获得了一个IEnumerator类型。我想通过它来循环使用以下方式如何遍历此IEnumerator

System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string,string>> 

    Ien = Concur_Dictionary.GetEnumerator(); 

    foreach (KeyValuePair<string, string> pair in Ien) -->Error here 
    { 
    } 

我收到以下错误

Error 4 foreach statement cannot operate on variables of type 'System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string,string>>' because 'System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string,string>>' does not contain a public definition for 'GetEnumerator' 

上我能如何通过这个IEnumerator的迭代有什么建议?

回答

5

您通常不想遍历IEnumerator;你只是遍历IEnumerable直接:

foreach (var pair in Concur_Dictionary) … 

如果由于某种原因,你没有给IEnumerable访问,你可以这样做:

while (Ien.MoveNext()) 
{ 
    var pair = Ien.Current; 
    … 
} 
+0

那么在这种情况下,这很重要。由于它的线程安全。所以我需要遍历IEnumerator – MistyD 2013-02-20 08:23:17

+0

@MistyD:'foreach'语句在后台调用'GetEnumerator()'。 – 2013-02-20 08:26:04

+0

感谢您的支持 – MistyD 2013-02-20 08:29:07

1

您可以使用它MoveNext()

var enumerator = getInt().GetEnumerator(); 
while(enumerator.MoveNext()) 
{ 
    //Line of codes.. 
} 

你可以做这样的事情。

或者这可以做到。

foreach (var item in collection) 
{ 
    // do your stuff 
} 

试试这个东西对我有效。