C# “帮助”;收集被修改;枚举操作可能无法执行;

C# “帮助”;收集被修改;枚举操作可能无法执行;,c#,collections,C#,Collections,当我使用下面的代码时,我得到一个“Collection was modified;enumeration operation may not execute”错误。如果我理解正确,我认为这意味着我不能枚举这个数据表,同时从中删除行。我的问题是,我还可以做些什么来实现从数据表中删除某些行的结果? 这是我的密码: // Now let's loop through the datatable and find any account with no // LYSMKW

当我使用下面的代码时,我得到一个“Collection was modified;enumeration operation may not execute”错误。如果我理解正确,我认为这意味着我不能枚举这个数据表,同时从中删除行。我的问题是,我还可以做些什么来实现从数据表中删除某些行的结果? 这是我的密码:

        // 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++;
        }
//现在让我们在datatable中循环,找到没有
//LYSMKWh值,且当前使用电量小于4000 KWh。我们会移除那些
//从数据表中。
currentRow=0;
foreach(resultsDT.Rows中的数据行)
{
if((字符串)resultsDT.Rows[currentRow][“LYSMKWh”]=“0”)
{
int intKWh=Convert.ToInt32(resultsDT.Rows[currentRow][“KWH”]);
如果(单位千瓦时<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();
}
for(int i=resultsDT.Rows.Count-1;i>=0;i--)
{
if((字符串)resultsDT.Rows[i][“LYSMKWh”]==“0”)
{
int intKWh=Convert.ToInt32(resultsDT.Rows[i][“KWH”]);
如果(单位千瓦时<5000)
{
resultsDT.Rows[i].Delete();
}
}
resultsDT.AcceptChanges();
}
2) 您可以将要删除的行添加到单独的集合中,然后在遍历整个原始集合后删除它们。这显然效率较低,所以我不必担心样本