.NET - 从列表中删除<T>在“foreach"循环中 [英] .NET - Remove from a List&lt;T&gt; within a &#39;foreach&#39; loop

查看:23
本文介绍了.NET - 从列表中删除<T>在“foreach"循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码,我希望看起来像这样:

I have code that I want to look like this:

List<Type> Os;

...

foreach (Type o in Os)
    if (o.cond)
        return;  // Quitting early is important for my case!
    else
        Os.Remove(o);

... // Other code

这不起作用,因为当您在该列表的 foreach 循环中时,您无法从列表中删除:

This doesn't work, because you cannot remove from the list when you are inside a foreach loop over that list:

有没有解决问题的通用方法?

Is there a common way to solve the problem?

如果需要,我可以切换到其他类型.

I can switch to a different type if needed.

选项 2:

List<Type> Os;

...

while (Os.Count != 0)
     if (Os[0].cond)
         return;
     else
         Os.RemoveAt(0);

... // Other code

丑陋,但应该管用.

推荐答案

您真的需要在 foreach 循环中执行此操作吗?

Do you really need to do this within a foreach loop?

这将获得与您的示例相同的结果,即,从列表中删除所有项目,直到第一个匹配条件的项目(如果没有一个项目与条件匹配,则删除所有项目).

This will achieve the same results as your examples, ie, remove all items from the list up until the first item that matches the condition (or remove all items if none of them match the condition).

int index = Os.FindIndex(x => x.cond);

if (index > 0)
    Os.RemoveRange(0, index);
else if (index == -1)
    Os.Clear();

这篇关于.NET - 从列表中删除<T>在“foreach"循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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