如何迭代正在修改的列表?
我有一个需要迭代的数据集中的行列表。
问题是迭代中的处理可能会从列表中删除一行或多行。
由于列表正在被修改,我无法使用 foreach() 循环。
但是,由于某些删除可能发生在我正在处理的元素之前,因此我也不能使用 for() 循环(即,如果我正在处理 element ,这会导致删除 element还有其他元素,我想不出一种方法来调整 i 以正确指向我正在处理的元素之后的元素)。
你会如何解决这个问题? 我目前的想法是始终处理列表中的第一个元素。 如果被删除,则处理新的第一个元素。 如果它没有被删除,则将其移动到“alreadyProcessed”列表,并处理新的第一个元素。
有更容易的方法吗?
I have a list of rows from a dataset that I need to iterate through.
The problem is that the processing in the iteration may delete one or more rows from the list.
Since the list is being modified, I can't use a foreach() loop.
But since it is possible some of the deletions may occur at elements BEFORE the one I'm processing, I also can't use a for() loop (i.e, if I'm processing element , and that results in the deletion of element and also other elements , I can't think of a way to adjust i to correctly point to the element following the one that I was processing).
How would you tackle this problem? My current thought it is to always process the first element in the list. If it gets deleted, process the new first element. If it doesn't get deleted, the move it to an "alreadyProcessed" list, and process the new first element.
Is there an easier way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常,这是通过反向循环完成的:
这会导致以相反的顺序处理项目,因此如果删除项目,它不会影响任何仍待处理的项目的位置。
Typically this is done with a reverse loop:
This causes the items to be processed in reverse order, so if you delete an item, it does not affect the position of any items still to be processed.
当修改我正在迭代的列表时,我总是发现最简单的方法是使用我想要保留的项目构建一个新列表,然后使用新列表执行我要做的任何事情。
我想,这实际上取决于完成后您对数据的处理方式。
When modifying a list I'm iterating through, I always find it easiest to build a new list with the items I want to keep, and then use the new list to do whatever it was I was going to do.
It really depends on what you're doing with the data when you're done, I suppose.
如果您可以将数据放入链接列表中,那就太好了。
If you can get your data into a linked list, you're golden.