Can you remove an item from a Listlt;gt; whilst iterating through it in C#(你能从列表中删除一个项目吗lt;gt;在 C# 中迭代它时)
问题描述
您能否在迭代时从列表中删除一个项目<>?这会起作用吗,还是有更好的方法来做到这一点?
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# 中迭代它时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你能从列表中删除一个项目吗<>在 C# 中迭代它时


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01