本文介紹了收藏已修改;枚舉操作可能無法在 ArrayList 中執行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試從 ArrayList
中刪除一個項目,但我得到了這個異常:集合被修改;枚舉操作可能無法執行.
I'm trying to remove an item from an ArrayList
and I get this Exception:
Collection was modified; enumeration operation may not execute.
有什么想法嗎?
推薦答案
您在 foreach
期間刪除了項目,是嗎?簡單地說,你不能.這里有一些常見的選項:
You are removing the item during a foreach
, yes? Simply, you can't. There are a few common options here:
- 將
List<T>
和RemoveAll
與謂詞一起使用 按索引向后迭代,刪除匹配項
- use
List<T>
andRemoveAll
with a predicate iterate backwards by index, removing matching items
for(int i = list.Count - 1; i >= 0; i--) {
if({some test}) list.RemoveAt(i);
}
使用foreach
,并將匹配項放入第二個列表;現在枚舉第二個列表并從第一個列表中刪除這些項目(如果你明白我的意思)
use foreach
, and put matching items into a second list; now enumerate the second list and remove those items from the first (if you see what I mean)
這篇關于收藏已修改;枚舉操作可能無法在 ArrayList 中執行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!