.NET - 从列表&LT删除; T>内“的foreach”循环 [英] .NET - Remove from a List<T> within a 'foreach' loop

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

问题描述

我有code,我的需要的看起来是这样的:

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

丑陋,但它应该工作。

Ugly, but it should work.

推荐答案

你真的需要一个的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 - 从列表&LT删除; T&GT;内“的foreach”循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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