Collection已修改,枚举操作可能无法执行
The Collection has modified, the enumeration operation may not execute
我有一本字典,我想通过删除前一个字典并添加一个新字典来修改它的键,然后一次又一次地迭代它。
这是 dictionary
的声明
Dictionary<string, List<Entity>> SuggestedDictionary = new Dictionary<string, List<Entity>>
并且:另一个字典是:
Dictionary<string, List<Entity>> CopyDataDict = new Dictionary<string, List<Entity>>
之后,我使用 Dict.Add() 将数据填充到字典中。
List<Entity> list = db.books.ToList();
foreach(var l in list)
{
list.Add(l);
}
SuggestedDictionary.Add("Key", list);
CopyDataDict.Add("Key", list);
然后我按如下方式遍历数据:
foreach (var entry in CopyDataDict.Values.ToList())
{
for (int i = 2; i < 15; i++) //just 14 items will be added
{
foreach (var container in SuggestedDictionary.Keys)
{
rec.Add(new Recommendations() { bookName = container, Rate = CalculatePearsonCorrelation(bkName, container) });
}
SuggestedDictionary.Remove(SuggestedDictionary.Keys.ToString());
if (!SuggestedDictionary.ContainsKey(entry[i].bookName))
{
SuggestedDictionary.Add(entry[i].bookName, list);
}
}
当我运行代码时,它说The Collection has been modified enumeration operator may not execute。我该如何修复它或者是否有更好的解决方案来做同样的事情。
我只是运行你的代码,它与添加或删除密钥无关。填充列表对象时出现错误
List<Entity> list = db.books.ToList();
foreach(var l in list)
{
list.Add(l);
}
您已经有了图书清单,那么 foreach 循环的目的是什么?
您收到错误是因为您在枚举列表时添加了新对象,这是不允许的,因为它将是不定式
您的问题始于以下代码:
List<Entity> list = new DomainModelDbContext().books.ToList();
foreach (var l in list)
{
list.Add(l); // Runtime error
}
一般来说,您不能在使用 foreach 循环遍历集合或字典时添加或删除项目。如果您使用其他类型的循环,例如 for(...)、while 循环等,则不会出现此问题
我有一本字典,我想通过删除前一个字典并添加一个新字典来修改它的键,然后一次又一次地迭代它。 这是 dictionary
的声明 Dictionary<string, List<Entity>> SuggestedDictionary = new Dictionary<string, List<Entity>>
并且:另一个字典是:
Dictionary<string, List<Entity>> CopyDataDict = new Dictionary<string, List<Entity>>
之后,我使用 Dict.Add() 将数据填充到字典中。
List<Entity> list = db.books.ToList();
foreach(var l in list)
{
list.Add(l);
}
SuggestedDictionary.Add("Key", list);
CopyDataDict.Add("Key", list);
然后我按如下方式遍历数据:
foreach (var entry in CopyDataDict.Values.ToList())
{
for (int i = 2; i < 15; i++) //just 14 items will be added
{
foreach (var container in SuggestedDictionary.Keys)
{
rec.Add(new Recommendations() { bookName = container, Rate = CalculatePearsonCorrelation(bkName, container) });
}
SuggestedDictionary.Remove(SuggestedDictionary.Keys.ToString());
if (!SuggestedDictionary.ContainsKey(entry[i].bookName))
{
SuggestedDictionary.Add(entry[i].bookName, list);
}
}
当我运行代码时,它说The Collection has been modified enumeration operator may not execute。我该如何修复它或者是否有更好的解决方案来做同样的事情。
我只是运行你的代码,它与添加或删除密钥无关。填充列表对象时出现错误
List<Entity> list = db.books.ToList();
foreach(var l in list)
{
list.Add(l);
}
您已经有了图书清单,那么 foreach 循环的目的是什么?
您收到错误是因为您在枚举列表时添加了新对象,这是不允许的,因为它将是不定式
您的问题始于以下代码:
List<Entity> list = new DomainModelDbContext().books.ToList();
foreach (var l in list)
{
list.Add(l); // Runtime error
}
一般来说,您不能在使用 foreach 循环遍历集合或字典时添加或删除项目。如果您使用其他类型的循环,例如 for(...)、while 循环等,则不会出现此问题