Reputation: 1786
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.
Upvotes: 0
Views: 2907
Reputation: 1321
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);
}
}
Upvotes: 1
Reputation: 89102
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--;
}
Upvotes: 1