如何在修改列表时遍历 Xamarin.Forms.Maps Map.Pins 列表?

How can I iterate over a Xamarin.Forms.Maps Map.Pins list while modifying the list?

我正在开发一个 Xamarin.Forms 应用程序,它利用了地图包。 Map 对象包含一个 IList Pins,它存储包含 Label、Position 和其他属性的 Pin 对象列表。我正在尝试通过将它们的位置与包含相同属性(ID、位置等)的自定义对象集合以及它们是否再存在于此列表中并相应地删除它们来更新此 Pins 列表。

为了详细说明,每次更新时,我想遍历 Pin 图列表,删除不再对应于集合中的对象的任何图钉,添加与集合中的新对象对应的任何图钉,并更改相应对象的位置已更改的任何图钉的位置。

我试图通过遍历 Pin 图并相应地进行比较,同时在必要时删除、添加和更改 Pin 图来做到这一点。这里的问题是每次删除 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 列表的副本以在修改原始列表时迭代,都不能解决这个问题。

我知道其中一些解决方案有效,因为我在比较我的自定义对象列表时使用它们来解决这个问题,但出于某种原因,其中 none 似乎适用于 Map.Pins 列表。谁能指出我可能做错了什么,或者是否有关于 Map.Pins 列表的一些细节将其排除在这些解决方案之外?还有其他方法可以解决这个问题吗?

参考这里的方法,在代码中,我尝试实现 "remove pins that should no longer exist" 功能:

.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 循环方法起作用,您需要倒数,否则每次删除项目时您的索引都会被丢弃。