为什么我会收到"集合已修改;枚举操作可能不会执行"如果不修改枚举集? [英] Why am I getting "Collection was modified; enumeration operation may not execute" when not modifying the enumerated collection?

查看:149
本文介绍了为什么我会收到"集合已修改;枚举操作可能不会执行"如果不修改枚举集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符串的两个集合:CollectionA是存储在系统中的对象的一个​​StringCollection属性,而CollectionB是在运行时所产生的列表。 CollectionA需要更新,如果有任何差异,以匹配CollectionB。所以,我制定了我的预期是一个简单的LINQ的方法来执行删除操作。

I have two collections of strings: CollectionA is a StringCollection property of an object stored in the system, while CollectionB is a List generated at runtime. CollectionA needs to be updated to match CollectionB if there are any differences. So I devised what I expected to be a simple LINQ method to perform the removal.

var strDifferences = CollectionA.Where(foo => !CollectionB.Contains(foo));
foreach (var strVar in strDifferences) { CollectionA.Remove(strVar); }



不过,我得到一个集合被修改;枚举操作可能不执行错误的strDifferences ......即使它是一个独立的枚举从集合被修改!我本来想出这个的明确的规避这个错误,因为我第一次执行将产生它(因为我是跨 CollectionA 列举,只是取出时!CollectionB.Contains(STR))。任何人都可以摆脱一些洞察为什么这个枚举失败的原因?

But I am getting a "Collection was modified; enumeration operation may not execute" error on strDifferences... even though it is a separate enumerable from the collection being modified! I originally devised this explicitly to evade this error, as my first implementation would produce it (as I was enumerating across CollectionA and just removing when !CollectionB.Contains(str)). Can anyone shed some insight into why this enumeration is failing?

推荐答案

两者不是完全独立的。 其中,不会使收集的单独副本。它在内部保持原来的集合的引用,当你要求他们从中获取的元素。

The two are not completely separate. Where does not make a separate copy of the collection. It internally keeps a reference to the original collection and fetches elements from it as you request them.

您可以通过添加解决您的问题了ToList() 强制其中,立即通过集合进行迭代。

You can solve your problem by adding ToList() to force Where to iterate through the collection immediately.

var strDifferences = CollectionA
    .Where(foo => !CollectionB.Contains(foo))
    .ToList();

这篇关于为什么我会收到"集合已修改;枚举操作可能不会执行"如果不修改枚举集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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