c# - 帮助解决 "Collection was modified; enumeration operation might not execute."

标签 c# collections

<分区>

当我使用以下代码时,出现“集合已修改;枚举操作可能无法执行”错误。如果我理解正确,我认为这意味着我无法枚举此数据表并同时从中删除行。我的问题是,我还能做些什么来实现从我的数据表中删除某些行的结果? 这是我的代码:

        // Now let's loop through the datatable and find any account with no
        // LYSMKWh value and less than 4000 KWh current usage.  We'll remove those
        // from the datatable.
        currentRow = 0;
        foreach (DataRow row in resultsDT.Rows)
        {
            if ((string)resultsDT.Rows[currentRow]["LYSMKWh"] == "0")
            {
                int intKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["KWH"]);
                if (intKWh < 5000)
                {
                    resultsDT.Rows[currentRow].Delete();                        
                }
            }
            resultsDT.AcceptChanges();
            currentRow++;
        }

最佳答案

您可以执行以下两项操作之一:

1) 您可以使用 for 循环以相反的顺序遍历集合并内联删除行:

for(int i = resultsDT.Rows.Count - 1; i >= 0; i--)
{
    if ((string)resultsDT.Rows[i]["LYSMKWh"] == "0")
    {
        int intKWh = Convert.ToInt32(resultsDT.Rows[i]["KWH"]);
        if (intKWh < 5000)
        {
            resultsDT.Rows[i].Delete();                        
        }
    }
    resultsDT.AcceptChanges();
}

2) 您可以将要删除的行添加到单独的集合中,然后在遍历整个原始集合后将其删除。这显然效率较低,所以我不会担心样本。

关于c# - 帮助解决 "Collection was modified; enumeration operation might not execute.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109806/

相关文章:

c# - 从 RouteData 生成格式化的友好 URL

c# - UrlHelper 在生成 URI 时不使用引用主机

c# - TextBox 控件使用什么事件来在按下 enter 时发出文本更改信号?

c# - 使用 C# 3.0,如何使用泛型集合编写基于接口(interface)的代码?

c# - 通过 SignalR 发送不同对象的列表

Java:从集合中获取范围内的值

java - Jaxb 解码 : not getting my collection elements

java - 无法理解 PriorityQueue 如何改变排序顺序?

forms - 表单集合上的 ZF2 对象绑定(bind)

c# - 有没有办法将vba宏代码添加到excel中?