遍历列表时可以修改列表吗? [英] Possible to modify a List while iterating through it?
本文介绍了遍历列表时可以修改列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
foreach (var depthCard in depthCards)
{
var card = InternalGetCard(db, depthCard.CardId);
var set = InternalGetSet(db, (int)card.ParentSetId);
var depthArray = InternalGetDepthArrayForCard(db, set.SetId);
foreach (var cardToUpdate in set.Cards)
{
// do stuff
SaveChanges(db);
depthCards.Remove(depthCardToUpdate); // since I already took care of it here, remove from depthCards
}
}
但这不起作用,因为我正在循环中间修改集合。我的问题是…是否存在某种允许这种访问方式的集合?
This isn't working though because I'm modifying the collection in the middle of a loop. My question is… is there some type of collection that does allow this type of access?
我不想 ToList()
depthCards
,因为我已经有了它们,并且我想要在迭代时修改该列表。
I don't want to ToList()
the depthCards
because I already have them and I want to modify that list as I'm iterating. Is it possible?
推荐答案
可能的方法是向后迭代:
It's possible, the trick is to iterate backwards:
for (int i = depthCards.Count - 1; i >= 0; i--) {
if (depthCards[i] == something) { // condition to remove element, if applicable
depthCards.RemoveAt(i);
}
}
这篇关于遍历列表时可以修改列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文