Help with "Collection was modified; enumeration operation might not execute." [duplicate]
When I use the following code, I'm getting a "Collection wa开发者_运维百科s modified; enumeration operation might not execute" error. If I understand this correctly, I think it means that I can't enumerate over this datatable and delete rows from it at the same time. My question is, what else can I do to achieve the result of deleting certain rows from my datatable? Here's my code:
// 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++;
}
You can do one of two things:
1) You can iterate over the collection in reverse order using a for loop and remove the rows inline:
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) You can add the rows you want to remove to a separate collection and then remove them after you iterate over the entire original collection. This is obviously less efficient so I'm not going to worry about a sample.
精彩评论