List使用Foreach 修改集合时,会报错的解决方案 (Error: Collection was modified; enumeration operation may not execute. )

当用foreach遍历Collection时,如果对Collection有Add或者Remove操作时,会发生以下运行时错误:

"Collection was modified; enumeration operation may not execute." 如下所示:

 
[c-sharp] view plaincopy

    List<string> list = new List<string>();  
    for (int i = 0; i < 10; i++)  
    {  
        list.Add(i.ToString());  
    }  
      
    foreach (string str in list)  
    {  
        //will throw InvalidOperationException in runtime.  
        list.Remove(str);  
    }  

 

究其原因,是因为Collection返回的IEnumerator把当前的属性暴露为只读属性,所以对其的修改会导致运行时错误,只需要把foreach改为for来遍历就好了。

 

对于Hashtable,由于没有提供[]操作符来供for遍历,可以先把item存入到一个array中,然后再对其进行Remove或Add操作,如下:

[c-sharp] view plaincopy

    Hashtable ht = new Hashtable();  
    for(int i=0;i<10;i++)  
    {  
        ht.Add(i, i);  
    }  
      
    List<object> keys = new List<object>();  
    foreach (DictionaryEntry de in ht)  
    {  
        /* 
        operations for ht 
        * */  
        //store related keys  
        keys.Add(de);  
    }  
      
    //another for loop to operate ht  
    for (int i = 0; i < keys.Count; i++)  
    {  
        /* 
        operations for tagged keys 
        */  
    }  
原文地址:https://www.cnblogs.com/haoliansheng/p/3229774.html