有效地删除从内部“的foreach”项目 [英] Efficiently deleting item from within 'foreach'

查看:112
本文介绍了有效地删除从内部“的foreach”项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,尽我所能的事是:

For now, the best I could thing of is:

bool oneMoreTime = true;
while (oneMoreTime)
{
    ItemType toDelete=null;
    oneMoreTime=false;
    foreach (ItemType item in collection)
    {
        if (ShouldBeDeleted(item))
        {
            toDelete=item;
            break;
        }
    }
    if (toDelete!=null)
    {
        collection.Remove(toDelete);
        oneMoreTime=true;
    }
}

我知道,我在这里至少有一个额外的变量,但我把它提高了算法的可读性。

I know that I have at least one extra variable here, but I included it to improve readability of the 'algorithm'.

推荐答案

在removeall过的方法是最好的。

The "RemoveAll" method is best.

另一种常见的方法是:

var itemsToBeDeleted = collection.Where(i=>ShouldBeDeleted(i)).ToList();
foreach(var itemToBeDeleted in itemsToBeDeleted)
    collection.Remove(itemToBeDeleted);

另一种常见的方法是使用for循环,但要确保你去的向后的:

for (int i = collection.Count - 1; i >= 0; --i)
    if (ShouldBeDeleted(collection[i]))
        collection.RemoveAt(i);

另一种常见的方法是补充,是的没有的被转移到新的集合中的项目:

Another common technique is to add the items that are not being removed to a new collection:

var newCollection = new List<whatever>();
foreach(var item in collection.Where(i=>!ShouldBeDeleted(i))
    newCollection.Add(item);

和现在你有两个集合。我特别喜欢,如果你想结束了两个集合的技术是使用一成不变的数据结构。带有不可变的数据结构,去除的项目不改变的数据结构;它给你回一个新的数据结构(即重新使用从旧位,如果可能的话),不具有已删除的项目。随着不可变的数据结构,你不改变你遍历的事情,所以没有问题:

And now you have two collections. A technique I particularly like if you want to end up with two collections is to use immutable data structures. With an immutable data structure, "removing" an item does not change the data structure; it gives you back a new data structure (that re-uses bits from the old one, if possible) that does not have the item you removed. With immutable data structures you are not modifying the thing you're iterating over, so there's no problem:

var newCollection = oldCollection;
foreach(var item in oldCollection.Where(i=>ShouldBeDeleted(i))
    newCollection = newCollection.Remove(item);

var newCollection = ImmutableCollection<whatever>.Empty;
foreach(var item in oldCollection.Where(i=>!ShouldBeDeleted(i))
    newCollection = newCollection.Add(item);

当你做,你有两个集合。新的人有删除的项目,旧的是一样的,因为它曾经是。

And when you're done, you have two collections. The new one has the items removed, the old one is the same as it ever was.

这篇关于有效地删除从内部“的foreach”项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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