收集被修改;枚举操作可能无法执行。 [英] Collection was modified; enumeration operation might not execute.

查看:125
本文介绍了收集被修改;枚举操作可能无法执行。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我试图遍历一个DataTable来查找AccountNo等于传入的数字的每一行。 />


我现在收到以下错误:



Hello,

I am trying to loop through a DataTable to find each row where the "AccountNo" is equal to a number that is passed in.

I am getting the following error now:

Collection was modified; enumeration operation might not execute.





代码在此循环中出错:





The code has errored on this loop:

For Each DataRow In dt.Rows

            RowNumber = RowNumber + 1

            If DataRow("AccountNo").ToString() = CustomerIDForHistory Then

                Dim output As String = DataRow.ToString.ElementAt(RowNumber)

                dt.Rows.Add(output)

            End If
        Next







感谢Glen




Thanks Glen

推荐答案

如果你真的需要在循环中添加项目,那么你应该(正确地)使用另一种循环(例如 for ,或,而,根据您的需要)迭代DataTable集合的项目,例如



If you really need to add items inside the loop then you should (properly) use another kind of loop (for instance a for, or a while, depending on your needs) to iterate on the items of the DataTable collection, e.g.

// this is most likely what you want to do, that is: NOT iterate on the newly inserted items
int COUNT = dt.Rows.Count;
for (int r = 0; r<COUNT; ++r)
{
  DataRow dr = dr.Rows[r];
  //...
}


你不能改变你当前循环的集合!



所以在dt.Rows中添加一个值,当你运行一个每个在dt.Rows ..抛出那个错误



greets
You can not change the Collection you currently loop through !

so adding a value to dt.Rows, while you run a for each on dt.Rows.. throws that error

greets


正确的方式也最容易解析或循环dictionary是将它的键放在List中,然后使用这个键列表遍历字典。



The right way and also easiest to parse or loop a dictionary is to get its keys in a List and then loop through the dictionary using this key-list.

List keyList = new List<int>(Dictionary.Keys);foreach (key in keys)
{
  // Now we can perform any modification wh values of dictionary.
  Dictionary[key] = Dictionary[key] - 1;
}</int>





这是一篇关于此的详细博文:示例在这里


这篇关于收集被修改;枚举操作可能无法执行。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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