如何从一个泛型列表在遍历它删除元素? [英] How to remove elements from a generic list while iterating over it?

查看:128
本文介绍了如何从一个泛型列表在遍历它删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个更好的模式的与每个需要处理的元素列表的工作,然后根据结果从列表中删除。

I am looking for a better pattern for working with a list of elements which each need processed and then depending on the outcome are removed from the list.

您不能使用上卸下摆臂(元素)的foreach(在X VAR元素)(因为它导致集合已修改;枚举操作可能不会执行除外)......你也不能使用的for(int i = 0; I< elements.Count();我++) .RemoveAt(我),因为它会破坏在收集相对你的当前位置 I

You can't use .Remove(element) inside a foreach (var element in X) (because it results in Collection was modified; enumeration operation may not execute. exception)... you also can't use for (int i = 0; i < elements.Count(); i++) and .RemoveAt(i) because it disrupts your current position in the collection relative to i.

有一种优雅的方式来做到这一点?

Is there an elegant way to do this?

推荐答案

有一个for循环迭代的反向列表:

Iterate your list in reverse with a for loop:

for (int i = safePendingList.Count - 1; i >= 0; i--)
{
    // some code
    // safePendingList.RemoveAt(i);
}

例如:

var list = new List<int>(Enumerable.Range(1, 10));
for (int i = list.Count - 1; i >= 0; i--)
{
    if (list[i] > 5)
    	list.RemoveAt(i);
}
list.ForEach(i => Console.WriteLine(i));

另外,你可以使用 RemoveAll方法了predicate要测试的

Alternately, you can use the RemoveAll method with a predicate to test against:

safePendingList.RemoveAll(item => item.Value == someValue);

下面是一个简单的例子来说明:

Here's a simplified example to demonstrate:

var list = new List<int>(Enumerable.Range(1, 10));
Console.WriteLine("Before:");
list.ForEach(i => Console.WriteLine(i));
list.RemoveAll(i => i > 5);
Console.WriteLine("After:");
list.ForEach(i => Console.WriteLine(i));

这篇关于如何从一个泛型列表在遍历它删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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