你能从列表中删除一个项目吗?在 C# 中遍历它 [英] Can you remove an item from a List<> whilst iterating through it in C#

查看:22
本文介绍了你能从列表中删除一个项目吗?在 C# 中遍历它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能在遍历 List<> 的同时删除它吗?这会奏效,还是有更好的方法?

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.

推荐答案

Edit:澄清一下,问题是关于 Silverlight,它显然不支持 删除列表中的所有`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# 中遍历它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆