问题描述
我试图从我的 DataTable
dt
中删除一些行,我得到上述异常:
I am trying to remove some rows from my DataTable
dt
in a loop where I get 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
code> failBatch 都是 DataTable
克隆的 dt
。
successBatch
and failBatch
are both DataTable
clones of dt
.
在其他问题中,我们正在处理一个 foreach
循环。为什么会出现此错误?
In the other questions where this error has been asked, we are dealing with a foreach
loop. Why does this error occur?
堆栈跟踪
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)
推荐答案
您正在更改集合中的元素(你的dataTable),然后用foreach循环它。
You are changing the elements in the collection (your dataTable) while looping over it with foreach.
Foreach查询枚举器并要求下一个元素。如果删除项目,枚举器的状态将变为无效。调查员必须存储一些日期,指明其当前位置。
Foreach queries the enumerator and asks for the next element. If you remove an item the enumerator's state becomes invalid. An enumerator has to store some date indicating where its current position.
您不应该这样做。也许使用另一个集合来跟踪更改或使用(阅读链接中的类)
You should not do this. Maybe use another collection to keep track of changes or use concurrent collections (read about the classes in the link)
这篇关于收藏品已修改;枚举操作可能无法执行“除外”操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!