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# 中迭代它时
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- WPF 模态进度窗口 2022-01-01
