The collection has been changed; enumeration operation may fail on exception operation
I am trying to remove some lines from mine DataTable
dt
in a loop where I am getting the above exception:
while (dt.Rows.Count > 0 && retry < Globals.PushRetryLimit)
{
var query = dt.AsEnumerable().Except(successBatch.AsEnumerable(), DataRowComparer.Default)
.AsEnumerable().Except(failBatch.AsEnumerable(), DataRowComparer.Default);
if (dt.AsEnumerable().Any())
dt = query.CopyToDataTable();
}
successBatch
and failBatch
are DataTable
clones dt
.
In other questions where this error has been asked, we are dealing with a loop foreach
. Why is this error occurring?
StackTrace:
at System.Data.DataTableExtensions.LoadTableFromEnumerable[T](IEnumerable`1 source, DataTable table, Nullable`1 options, FillErrorEventHandler errorHandler)
at System.Data.DataTableExtensions.CopyToDataTable[T](IEnumerable`1 source)
source to share
You are changing items in the collection (your dataTable) by iterating over it with a foreach.
Foreach asks for an enumerator and asks for the next item. If you remove the item, the state of the enumerator becomes invalid. The enumerator must store some date with the current position.
You shouldn't be doing this. Maybe use a different collection to track changes or use parallel collections (read about classes in the link)
source to share