gpt4 book ai didi

c# - 错误 : Collection was modified; enumeration operation may not execute

转载 作者:行者123 更新时间:2023-12-02 05:15:08 28 4
gpt4 key购买 nike

我一直在现场解决这个异常。我不明白如何在迭代时修改集合。我在方法开始时将所有内容复制到局部变量。

  public void Flush() {
var tempEntities = attachedEntities.Select(item => item).ToList();
attachedEntities.Clear();

var tempEntitiesToDelete = entitiesToDelete.Select(item => item).ToList();
entitiesToDelete.Clear();

foreach (var attachedEntity in tempEntities) {
var isTransient = (bool)GetPrivateField(attachedEntity.GetType(), attachedEntity, "isTransient");
if (isTransient)
db.Insert(attachedEntity);
else
db.Update(attachedEntity);
}

foreach (var entity in tempEntitiesToDelete)
db.Delete(entity);
}

堆栈跟踪

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].VerifyState () [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1 Enumerator[Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in <filename unknown>:0
at System.Linq.Enumerable <CreateSelectIterator>c__Iterator1D`2[Compass.Mobile.Core.DataAccess.IEntity,Compass.Mobile.Core.DataAccess.IEntity].MoveNext () [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0
at System.Collections.Generic.List`1[Compass.Mobile.Core.DataAccess.IEntity]..ctor (IEnumerable`1 collection) [0x00000] in <filename unknown>:0
at System.Linq.Enumerable.ToList[TSource] (IEnumerable`1 source) [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.DataAccess.Session.Flush () [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.DataAccess.Session.Commit () [0x00000] in <filename unknown>:0
at Compass.Mobile.Core.Bootstrap.CommandBus.Flush () [0x00000] in <filename unknown>:0

最佳答案

替换这个:

foreach (var entity in tempEntitiesToDelete)
db.Delete(entity);

与:

for (var i = tempEntitiesToDelete.Count - 1; i >= 0; i--)
db.Delete(tempEntitiesToDelete[i]);

当我尝试在循环中删除时遇到了这个问题;它试图修改项目列表。因此,向后循环为我修复了它。

关于c# - 错误 : Collection was modified; enumeration operation may not execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14779568/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com