0

I want to delete multiple items in an ObservableCollection in C#. My code is:

var item = (MoveDataModel)e.SelectedItem;
var answer = await DisplayAlert("Confirmation", "Are you sure you wish to delete " + item.value + "?", "Yes", "No");
        if (answer)
{
    var type = item.type;
    var value = item.value;

    foreach (var listItem in items)
    {
        if ((listItem.value == item.value) || (listItem.location == value && type == "Location"))
        {
            items.Remove(listItem);
            itemCount--;
        }
    }
}

The first iteration works fine. However, it hangs on

foreach (var listItem in items)

on the second pass. I'm not sure how to make it work.

Floyd Resler
  • 1,786
  • 3
  • 22
  • 41
  • Possible duplicate of [Collection was modified; enumeration operation may not execute](https://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – Steve Jul 05 '18 at 16:20

2 Answers2

1

you can't modify a collection while you're iterating over it. Try something like this (I haven't checked the syntax, may need some cleanup)

var removeList = items.Where(x => x.value == value).Where(y => y.type = type).ToList();

foreach(var i in removeList) {
  items.Remove(i);
  itemCount--;
}
Jason
  • 86,222
  • 15
  • 131
  • 146
1

Have your own counter, cycle backwards through the list so you wont have to readjust for indexes you removed.

System.Collections.ObjectModel.ObservableCollection<object> list = new System.Collections.ObjectModel.ObservableCollection<object>();
private void RemoveStuff()
{
    var i = list.Count - 1;
    for (; i <= 0; i--)
    {
        // some checks here to make sure this is the time you really want to remove
        list.Remove(i);
    }

}
Gauthier
  • 1,251
  • 10
  • 25