迭代时如何从通用列表中删除元素?

How to remove elements from a generic list while iterating over it?(迭代时如何从通用列表中删除元素?)
本文介绍了迭代时如何从通用列表中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找更好的 模式 来处理每个需要处理的元素列表,然后根据结果从列表中删除.

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 (var element in X) 中使用 .Remove(element) (因为它会导致 Collection 被修改;枚举操作可能无法执行. 异常)...您也不能使用 for (int i = 0; i < elements.Count(); i++).RemoveAt(i) 因为它会破坏您在集合中相对于 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 方法测试:

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));

这篇关于迭代时如何从通用列表中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)