我正在使用Xamarin.Forms应用程序,该应用程序利用Maps包。 Map对象包含一个IList Pins,它存储包含Label,Position和其他属性的Pin对象的列表。我正在尝试通过将其“位置”与包含相同属性(ID,位置等)以及它们是否已存在于此列表中的自定义对象的集合进行比较来更新此“引脚”列表,并相应地将其删除。
为了详细说明,每次更新时,我都要遍历Pins列表,删除不再与集合中的对象相对应的所有pin,添加与集合中的新对象相对应的所有pin,并更改其位置相应对象的位置已更改的引脚。
我正在尝试通过遍历Pins并进行相应的比较,同时在必要时移除,添加和更改Pins来进行此操作。这里的问题是,每次移除Pin时都会出现以下错误:
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code
Collection was modified; enumeration operation may not execute.
这在修改要迭代的列表时是可以预期的,但是所有可用于解决此问题的解决方案,例如在实例化foreach循环时使用Maps.Pins.ToList(),使用for循环而不是foreach循环,甚至创建Pins列表的副本以在修改原始文档时进行迭代,都无法解决此问题。
我知道其中一些解决方案有效,因为在比较我的自定义对象列表时,我已使用它们来解决此问题,但是由于某些原因,它们似乎都不适用于Map.Pins列表。谁能指出我可能做错了什么,或者是否有关于Map.Pins列表的某些详细信息将其排除在这些解决方案之外?还有其他方法可以解决此问题吗?
这里提供参考,我尝试通过代码来实现“删除不应该存在的引脚”功能:
。ToList()
foreach (Pin pin in map.Pins.ToList())
{
if (!newList.Any(x => x.ID == pin.Label))
{
Debug.WriteLine("Pin " + pin.Label + " is being removed.");
map.Pins.Remove(pin);
}
}
For循环
for (int i = 0; i < map.Pins.Count; i++) {
Debug.WriteLine(map.Pins[i].Label);
if (!newList.Any(x => x.ID == map.Pins[i].Label))
{
Debug.WriteLine("Pin " + map.Pins[i].Label + " is being removed.");
map.Pins.Remove(map.Pins[i]);
}
}
创建新列表
List<Pin> oldPins = new List<Pin>();
foreach (Pin pin in map.Pins)
{
oldPins.Add(pin);
}
foreach (Pin pin in oldPins)
{
if (!newList.Any(x => x.ID == pin.Label))
{
Debug.WriteLine("Pin " + pin.Label + " is being removed.");
map.Pins.Remove(pin);
}
}
// I tried this with the for loop solution as well
非常感谢
为了使for循环方法起作用,您需要倒数,否则每次删除项目时,索引都会被抛出。