最好的方式来枚举集合时的元素可以枚举过程中被删除 [英] Best way to enumerate collection when elements may be deleted during enumeration

查看:175
本文介绍了最好的方式来枚举集合时的元素可以枚举过程中被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些类的典型对象的集合,例如字符串的简单

There is a typical collection of some class objects e.g. string for a simplicity

IList<string> collection = new List<string>();

在某些功能需要收集,处理类对象进行操作和程序流程取决于从收集操作删除处理类对象的结果。

During the program flow some function needs to operate on the collection, process class object and depending on the result of operation remove processed class object from collection.

例如。下面的示例中的字符串,如果字符串为失败,然后删除该项目

E.g. following example of strings if string is "failed" then remove that item

foreach (string str in collection)
{
    // operate on the current class object
    // if str is not valid
    if (str == "failed")
        collection.Remove(str);
}

通过,导致异常的所有手段。 什么是环通有能力在枚举过程中删除所有元素的最好方法是什么?

By all means that leads to exception. What is the best way to loop thru all elements having ability to remove it during enumeration?

推荐答案

做索引的循环,但这样做反了,因为当你删除成员索引上游得到改变。

Do an indexed for loop, but do it backwards, because when you delete members the indexes upstream get changed.

例如,您的字符串集合例如:

e.g, for your string collection example:

for (int i = collection.Count() - 1; i >= 0; i--)
{
    // do some other stuff, then ...

    if (collection[i] == "failed")
        collection.RemoveAt(i);
}

注:如果您使用的是正向的循环,就可能会出现工作在第一,但每次删除后,它会跳过一个项目(的方式,因为指数得到删除之后重新编号)。因此,该错误的常见症状是,消除似乎工作,直到你得到两个相邻的。这可以是一个相当混乱的错误。这并不是说其曾经发生在我身上*咳嗽*

NB: if you use a forward for-loop, it may appear to work at first, but it will skip an item after each remove (because of the way indexes get renumbered after a remove). So a common symptom of that bug is that removes appear to work until you get two adjacent ones. That can be quite a confusing bug. Not that its ever happened to me *cough*

这篇关于最好的方式来枚举集合时的元素可以枚举过程中被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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