收集被修改;枚举操作可能无法执行

时间:2012-10-04 21:16:53

标签: c# foreach

我有以下代码。我试图删除记录,并在删除记录时抛出异常。 “集合已被修改;枚举操作可能无法执行。”

关于如何摆脱信息的任何想法。感谢你的时间。

//validClaimControlNo has valid ClaimControl Numbers.
List<string> validClaimControlNo = new List<string>();

int count = 0;
foreach (List<Field> f in records)
{
    foreach (Field fe in f)
    {
        if (i == 0)
            if (!(validClaimControlNo.Contains(fe.Value)))
            {
                //if this claim is not in the Valid list, Remove that Record
                records.RemoveAt(count);
            }
        i++;
    }
    i = 0;
    count++;
}

3 个答案:

答案 0 :(得分:4)

您无法从正在迭代的集合中删除项目。添加.ToList()将创建一个新列表,从而使其有效。

 foreach (List<Field> f in records.ToList())

另一种方法是向后迭代集合(你不需要额外的列表):

for(int i = records.Count - 1; i >= 0; i--)
{
   var f = records[i];

但是看看你的代码可以简化很多:

//Put the claim numbers into a set for fast lookup
var set = new HashSet<string>(validClaimControlNo);

//Remove undesired items
records.RemoveAll(f => f.Count > 0 && !set.Contains(f[0].Value));

答案 1 :(得分:2)

将您的foreach更改为:

foreach (List<Field> f in records.ToList())

答案 2 :(得分:1)

以最快的方式对你的收藏进行迭代是最快的方式。

for (int i = records.Count - 1; i >= 0; i--) { ... }