问题描述
您能否在迭代时从列表中删除一个项目<>?这会起作用吗,还是有更好的方法来做到这一点?
Can you remove an item from a List<> whilst iterating through it? Will this work, or is there a better way to do it?
我的代码:
foreach (var bullet in bullets)
{
if (bullet.Offscreen())
{
bullets.Remove(bullet);
}
}
-edit- 抱歉各位,这是给 Silverlight 游戏的.我没有意识到 silverlight 与 Compact Framework 不同.
-edit- Sorry guys, this is for a silverlight game. I didn't realise silverlight was different to the Compact Framework.
推荐答案
编辑:澄清一下,问题是关于 Silverlight,它显然不支持 RemoveAll on List`T.它在 完整框架、CF、XNA 2.0+ 版本中可用
Edit: to clarify, the question is regarding Silverlight, which apparently does not support RemoveAll on List`T. It is available in the full framework, CF, XNA versions 2.0+
您可以编写一个表达您的删除标准的 lambda:
You can write a lambda that expresses your removal criteria:
bullets.RemoveAll(bullet => bullet.Offscreen());
或者你可以选择你想要的,而不是删除你不想要的:
Or you can select the ones you do want, instead of removing the ones you don't:
bullets = bullets.Where(b => !b.OffScreen()).ToList();
或者使用索引器在序列中向后移动:
Or use the indexer to move backwards through the sequence:
for(int i=bullets.Count-1;i>=0;i--)
{
if(bullets[i].OffScreen())
{
bullets.RemoveAt(i);
}
}
这篇关于你能从列表中删除一个项目吗<>在 C# 中迭代它时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!